.find()之后,猫鼬填充函数不起作用

时间:2019-01-27 06:16:57

标签: node.js mongoose mongoose-populate

我试图查询多个用户配置文件,然后填充每个配置文件并将其发送到我的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'])填充它,并且它绝对可以正常工作很好。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

以下代码可能有效,在 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)
                }
            });
})