Categories
JavaScript Answers

How to run query after populate in Mongoose?

Spread the love

Sometimes, we want to run query after populate in Mongoose.

In this article, we’ll look at how to run query after populate in Mongoose.

How to run query after populate in Mongoose?

To run query after populate in Mongoose, we call populate with an object with the query.

For instance, we write

const query = Models.Item.find({});

query
  .desc('dateCreated')
  .populate('tags', null, {
    tagName: {
      $in: ['funny', 'politics']
    }
  })

to call populate with an object that has the field to query as the first argument and an object with the predicate data as the 3rd argument.

Therefore, we query the tags field to find the items with the tagName equal to 'funny' or 'politics' and populate each entry in the results with the query result from calling populate.

Conclusion

To run query after populate in Mongoose, we call populate with an object with the query.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *