猫鼬,你为什么要用填充而不是另一个发现



我猜是因为您通过向数据库发出1个请求而不是2个请求来节省资源。这有意义吗?如果我只填充1个字段,我是否应该使用populate(当填充超过1个字段时优势更明显)?

使用populate不会节省资源。在后台,mongoose可以根据需要多次调用数据库。考虑这个例子:

module.exports = function(){
    var UserSchema = new Schema({
        email : {type : String, required: true},
        password: {type: String, required: true}
    });
    return mongoose.model("User", UserSchema);
};

module.exports = function(){
    var AccountSchema = new Schema({
        number : {type : String, required: true},
        user: {type: Schema.Types.ObjectId, ref: 'User'}
    });
    return mongoose.model("Account", AccountSchema);
};

mongoose.set('debug', true);  //to see queries mongoose is using behind the scenes
Account.find({}, function(err, res){
    console.log(res)
}).populate("user")

除了结果,您将在控制台上看到如下内容:

Mongoose: accounts.find({}, { fields: undefined })
Mongoose: users.find({ _id: { '$in': [ ObjectId("5807d6d6aa66d7633a5d7025"), ObjectId("5807d6d6aa66d7633a5d7026"), ObjectId("5807d709aa66d7633a5d7027") ] } }, { fields: undefined })

这是猫鼬查找帐户文档,然后为每个帐户查找用户。

它为你节省了大量的代码,我不明白为什么你不应该使用它,不管你填充的字段的数量

最新更新