【问题标题】:find().populate() vs find().find() in mongoose猫鼬中的 find().populate() 与 find().find()
【发布时间】: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


    【解决方案1】:

    Mongoose 填充并不神奇,因为它仍然是客户端查找,而 $lookup 是服务器端查找。

    对于单个 findById 查询,比较这 2 个语句可能看不到任何好处。

    当您使用 find().populate() 等查询返回多个记录时,您可以看到 .populate 的好处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-18
      • 2015-04-01
      • 1970-01-01
      • 2014-05-30
      • 2019-07-10
      • 1970-01-01
      • 2020-12-01
      相关资源
      最近更新 更多