user3768533
user3768533

Reputation: 1347

Mongoose why would you use populate over another find?

I'm guessing because you save resources by making 1 request instead of 2 to the database. Is this significant? Should I care to use populate if I'm populating only 1 field (the advantage is clearer when you populate more than 1)?

Upvotes: 0

Views: 103

Answers (1)

Talha Awan
Talha Awan

Reputation: 4619

You don't save resources by using populate. Under the hood mongoose calls the database as many times as required. Consider the example:

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")

Apart from the results, you'll see something like this on console:

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

That's mongoose finding account documents and then user for each one of them.

It's saving you a lot of code and I don't see why you should not use it irrespective of the number of fields you're populating.

Upvotes: 1

Related Questions