Created
July 23, 2019 15:29
-
-
Save vainamov/4b57e696ab8506dd0e07245ec95f0b00 to your computer and use it in GitHub Desktop.
Mongoose Embed Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextFunction, Request, Response } from "express"; | |
declare module "express" { | |
interface Request { | |
embed: { path: String, fields?: String }[] | |
} | |
} | |
export function EmbedMiddleware(req: Request, res: Response, next: NextFunction): void { | |
req.embed = []; | |
if (req.query.embed) { | |
let embedQueries: String[] = req.query.embed.split(","); | |
embedQueries.forEach(query => { | |
if (query.includes(".")) { | |
req.embed.push({ path: query.split(".")[0], fields: query.split(".")[1].replace("+", " ") }) | |
} else { | |
req.embed.push({ path: query }); | |
} | |
}); | |
} | |
next(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
router.get("/", (req: Request, res, next) => { | |
let query = Model.find(); | |
req.embed.forEach(embed => { | |
query.populate(embed.path, embed.fields); | |
}); | |
query.then(results => { | |
res.send(results); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment