Skip to content

Instantly share code, notes, and snippets.

@vainamov
Created July 23, 2019 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vainamov/4b57e696ab8506dd0e07245ec95f0b00 to your computer and use it in GitHub Desktop.
Save vainamov/4b57e696ab8506dd0e07245ec95f0b00 to your computer and use it in GitHub Desktop.
Mongoose Embed Middleware
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();
}
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