mongoosemongoose-populate

Chaining populate in mongoose causes error


I have a problem with chaining populate in Mongoose.

I have a pet schema and I have declared a method like this:

petSchema.methods.populateForLang = async function(lang) {
...
}

Inside this method, I am trying to populate some docs, and this populate works fine:

return await this.populate({path:'type', select: 'title en'});

I also have this populate that works fine:

return await this.populate({path: 'petGender', select: 'title en'});

But when I chain them together:

await this.populate({path: 'petGender', select: 'title en'}).populate({path:'type', select: 'title en'});

I get the error:

this.populate(...).populate is not a function

What is going on?


Solution

  • If you need to populate more than one schema, then you can populate them in one as an array model:

    await this.populate([
        { path: 'petGender', select: 'title en' }, 
        { path:'type', select: 'title en' }
    ]);