Fcoder
Fcoder

Reputation: 9216

Where clause on mongoose populate

in a Node.js App, i use this code to fetch some data:

Users.find({user_enabled:true}).populate('books')...

but right now i have a problem. i just want users with books that are in english language.

right now i'm doing this: fetch all users and all books for them. then in a loop, i can check each book language.. this is not a good solution. i need something like Where clause in SQL. if a user don't have a book in english language, i don't need that user in the result. Mongodb/mongoose cant do this? j have to use a code after fetching all results for this?

i need something like this:

Users.find({user_enabled:true}).populate('books').where({'books.language':'en'})

Upvotes: 3

Views: 3625

Answers (1)

Lisa Gagarina
Lisa Gagarina

Reputation: 693

You can do this with match:

Users
  .find({ user_enabled: true })
  .populate({
    path: 'books',
    match: { 'language': 'en' },
  })
  .exec()

For more details check http://mongoosejs.com/docs/populate.html

Upvotes: 5

Related Questions