Home > Back-end >  hide a field of virtual population mongoose
hide a field of virtual population mongoose

Time:06-27

i have a comment collection and a post collection, and post schema are like this:

postSchema.virtual("comments", {
  ref: "Comment",
  localField: "_id",
  foreignField: "post",
})

and when i want to see comments of a post i use this:

   const post = await Post.findById(req.params.id);
    await post.populate("comments");
    res.send(post.comments);

i dont want to get email field of post.comments. i tried foreach delete key and it didnt work tnx for helping me

CodePudding user response:

You can use the regular field selection method for .populate with virtuals too:

await post.populate("comments", "-email");
// or if you want to exclude more than one field:
// await post.populate("comments", "-email -field2 -field3");

If you want to use positive selection (which fields should be included in the result), make sure that you always include the foreignField of the virtual (in this case post):

await post.populate("comments", "post field2 field3");
  • Related