【问题标题】:Mongoose populate function not working after .find()Mongoose 填充功能在 .find() 之后不起作用
【发布时间】:2019-06-20 11:39:39
【问题描述】:

我正在尝试查询多个用户配置文件,然后填充每个配置文件并将其发送到我的 Web 应用程序的客户端。但它失败得很惨。我已经完成了我的研究并尝试了所有方法,但它仍然不会填充它。这是我对后端的 axios 请求:

router.get("/all", (req, res) => {
errors = {}

Profile.find().populate('user', ['name', 'avatar'])
    .then(profiles => {
        if (!profiles) {
            errors.noprofile = " there are no profiles"
            res.status(404).json(errors)
        }
        else {
            res.json(profiles)
        }
    }).catch(err => res.json(errors))

})

这里没有填充配置文件的用户属性,我在我的配置文件集合中只获得了一个用户 ID。我使用 findOne({user:req.user.id}) 来获取特定用户,然后在我的文件中使用上面的 populate('user',['name','avatar']) 填充它,它绝对有效很好。

【问题讨论】:

标签: node.js mongoose mongoose-populate


【解决方案1】:

以下代码可能有效,在 path 选项中它应该是您的配置文件架构中可用的字段名称,在 model 选项中应该是参考模型的名称模型架构

router.get("/all", (req, res) => {
        errors = {}

        Profile.find({})
            .populate({
                path: 'user',
                model: 'user',
                select: 'name avatar',
            })
            .exec(function (err, profiles) {
                if (err) {
                    errors.noprofile = " there are no profiles"
                    res.status(404).json(errors)
                } else {
                    res.json(profiles)
                }
            });
})

【讨论】:

    【解决方案2】:

    .populate() 需要一个查询来附加自己,试试.find({})

    【讨论】:

      猜你喜欢
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2019-08-12
      • 1970-01-01
      • 2018-11-03
      • 2015-05-09
      • 2020-01-17
      相关资源
      最近更新 更多