Skip to content

Instantly share code, notes, and snippets.

@sandrabosk
Created May 16, 2020 05:33
Show Gist options
  • Save sandrabosk/c1c4c49a150e62f72e62bdf25848f9f4 to your computer and use it in GitHub Desktop.
Save sandrabosk/c1c4c49a150e62f72e62bdf25848f9f4 to your computer and use it in GitHub Desktop.

Basic use of the .populate() Mongoose method

The pattern for using .populate():

router.get('/list', (req, res, next) => {
  Model
    // prettier-ignore
    .find()
    .populate('property1')
    .then(/* everything went OK */)
    .catch(/* error */);
});

Double populate

If we need to perform double populate (populate one property and then in that property again populate some other property), the pattern is:

router.get('/posts', (req, res, next) => {
  Model1.find()
    .populate('property1 property2')
    .populate({
      path: 'property2',
      populate: {
        path: 'property3', // what are we populating inside "property2"
        model: 'Model2' // the property we are populating is actually which model
      }
    })
    .then(/* everything went OK */)
    .catch(/* error */);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment