有许多有关mongoose的populate功能的SO问题,但我无法找到证据表明这是可能的,如果是可能的,那么我做错了什么。
假设我正在制作一个博客。所有用户都可以撰写文章并在其他文章上发布评论。我选择以这种方式对事物进行建模:
用户:
当我想要加载一篇文章时,我可以使用mongooseJS的populate来加载一篇带有创建者的文章,如下所示: populate。
通过最新的版本,我发现article.comments[0].createdBy为空。我已经在数据库中验证了该评论存在一个由mongoose生成的对象ID,它匹配一个现有用户。
这是否可能? - 如果是,我哪里出错了? - 如果不是,有更好的方法吗?类似于这个 MongoDB问题,让我相信我走在正确的轨道上,但也许误用了mongoose?
假设我正在制作一个博客。所有用户都可以撰写文章并在其他文章上发布评论。我选择以这种方式对事物进行建模:
用户:
var UserSchema = new Schema({
name: String,
email: {
type: String,
unique: true
}
});
mongoose.model('User', UserSchema);
嵌入评论的文章:
var ArticleSchema = new Schema({
title: {
type: String
},
createdBy: {
type: Schema.ObjectId,
ref: 'User'
},
comments: [
commentsSchema
]
)};
var commentSchema = new Schema({
message: {
type: String
},
createdBy: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Article', ArticleSchema);
当我想要加载一篇文章时,我可以使用mongooseJS的populate来加载一篇带有创建者的文章,如下所示: populate。
Article
.findOne({_id: articleid})
.populate('createdBy', 'name email')
.exec(function(err,article) {
console.log('Created by %s', article.createdBy.name); // This works, yay.
});
但是如果我想使用populate同时加载评论和它们的创建者,comment.createdBy将是null:
Article
.findOne({_id: articleid})
.populate('createdBy', 'name email')
.populate('comments.createdBy', 'name email') //am I doing this correctly?
.exec(function(err,article) {
console.log('First comment by %s', article.comments[0].createdBy.name); // Error, createdBy is null.
});
通过最新的版本,我发现article.comments[0].createdBy为空。我已经在数据库中验证了该评论存在一个由mongoose生成的对象ID,它匹配一个现有用户。
这是否可能? - 如果是,我哪里出错了? - 如果不是,有更好的方法吗?类似于这个 MongoDB问题,让我相信我走在正确的轨道上,但也许误用了mongoose?