选择填充在猫鼬中的字段

时间:2020-04-10 13:35:38

标签: node.js mongodb mongoose mongodb-query mongoose-populate

我需要过滤用猫鼬select()函数填充时获得的结果的字段。我只需要title对象的contentimagePost字段以及name的{​​{1}}和avatar对象。

在User模式中,我创建了一个User,它引用了Post模式的virtual字段。

userId

2 个答案:

答案 0 :(得分:0)

您可以使用select方法从当前集合中选择所需的内容

关于填充字段,您可以将一个对象传递给populate方法以指示要填充的路径,然后从该集合中选择哪些项目

您的查询应该是这样的

Post.findById(id).select('title content image userId').populate({ path: 'userId', select: 'name avatar' })

请注意,我们需要在第一个选择中选择userId,以便可以在填充函数中使用它

答案 1 :(得分:0)

您可以遵循此准则

const post = await Post.findById(id)
      .select("+title +content +image")
      .populate('userId')


**Also You can use Aggregate: $project operator**