我正在尝试将完整的用户模型附加到我的评论部分中的每条评论中。由于 mongodb 没有联接,我一直在尝试找出如何使用 .populate() 从 Controller 添加用户对象。据我了解,要使用填充函数,您只需要做两件事。
- 在模型中定义一个引用。
- 对定义了 ref 的字段名称调用 .populate()。
我已将模型中的引用定义为“用户”模型:
var commentSchema = new mongoose.Schema({
author: { type: String, ref: 'User' },
description: String,
commentID: String,
hasParent: String,
parentComment: String,
timestamp: { type: Number, default: 0 },
});
然后我尝试将用户模型添加到评论对象的作者字段中:
Comment
.find()
.populate('author')
.exec(function (err, comments) {
console.log(comments);
});
我是否缺少一个步骤?我希望在每条评论的作者字段中看到带有完整用户对象的所有评论。
最佳答案
解决方案是从 mongodb 中删除评论集合。重新开始,它会按预期工作。如果有人遇到类似的问题,请尝试删除在向模型添加引用之前创建的对象集合。
关于javascript - 使用 .populate() mongodb Node.js 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880887/