如何在猫鼬子文档数组中查找字段?

问题描述 投票:0回答:1

我有很多这样的评论对象:

   "reviews": {
        "author": "5e9167c5303a530023bcae42",
        "rate": 5,
        "spoiler": false,
        "content": "This is a comment This is a comment This is a comment.",
        "createdAt": "2020-04-12T16:08:34.966Z",
        "updatedAt": "2020-04-12T16:08:34.966Z"
    },

我想实现的是查找author字段并获取用户数据,但是问题是我尝试使用的查找仅将其返回给我:

代码

 .lookup({
    from: 'users',
    localField: 'reviews.author',
    foreignField: '_id',
    as: 'reviews.author',
  })

响应:

Response of api

以任何方式在该字段中获取作者的数据?那就是作者的ID。

mongodb mongoose mongoose-populate
1个回答
0
投票

您应该在对服务器的请求上使用猫鼬的populate('author')方法,该服务器获取该作者的ID并将用户数据添加到猫鼬的响应中并且不要忘记以连接这两个集合的方式来设置架构在您的审阅模式中,应将引用添加到保存作者用户的模式中作者:{类型:Schema.Types.ObjectId,参考:“用户”},

© www.soinside.com 2019 - 2024. All rights reserved.