【发布时间】:2020-08-08 06:59:47
【问题描述】:
我想知道,在 mongoose ORM 中使用 populate 和使用 find 方法有什么区别。
假设我有两个模型。 1.用户和2.发布
mongoose.model('User', mongoose.Schema({
user : {type: String},
posts : [type: mongoose.SchemaTypes.ObjectId, ref: 'Post'}]
}))
和 Post 模型
mongoose.model('Post', mongoose.Schema({
user : {type: mongoose.SchemaTypes.ObjectId, ref: 'User'},
title : {type: String},
body : {type:String}
}))
我想生成所有用户的帖子。 我可以做到:
User.findById({_id:req._id}).then(currentUser => Post.find({user._id: currentUser}) ........
或者:
User.findById({_id:req._id}).populate('posts')
哪一种方法是正确的?两者有什么区别?
【问题讨论】:
标签: mongoose mongoose-schema mongoose-populate