首页 > 解决方案 > Mongoose 填充功能在 .find() 之后不起作用

问题描述

我正在尝试查询多个用户配置文件,然后填充每个配置文件并将其发送到我的 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.jsmongoosemongoose-populate

解决方案


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

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)
                }
            });
})

推荐阅读