node.js - 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']) 填充它,它绝对有效美好的。
解决方案
以下代码可能有效,在路径选项中,它应该是您的配置文件架构中可用的字段名称,在模型选项中,模型名称应该是参考模型架构
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)
}
});
})
推荐阅读
- java - 如何解决 java.lang.IllegalArgumentException
- r - 将参数传递给 R 中的自定义函数并进行过滤
- bash - 有没有办法找到目录中所有文件共享的行?
- ios - 如何从 mapView 中删除我的自定义注释?
- java - 为什么一些开发人员以这种方式分配原始整数?诠释我 = 0x0001
- python - Pandas 计算满足条件时列之间的时间差
- r - 文件未在 R 脚本中的适当位置创建
- python - 'module' 对象没有属性 'Serial' - Alicat
- javascript - 如果输入到输入中的字符串匹配它会显示一个带有 javascript 的 HTML 元素
- ios - Ionic 3 在 ios 12 上运行缓慢