我需要过滤用猫鼬select()
函数填充时获得的结果的字段。我只需要title
对象的content
,image
,Post
字段以及name
的{{1}}和avatar
对象。
在User模式中,我创建了一个User
,它引用了Post模式的virtual
字段。
userId
答案 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**