2

I have populated a virtual in Mongoose, the populated virtual will retrieve an array of objects.

 objects:{[name:'xxx',age:20],[name:'yyy',age:21],[name:'zzz', age:23]}

How do I make it that it only retrieves one element I specify?

...
.populate({
   path:'someVirtual',
   select:'objects', //get only the 'objects' array
   options: {where:'objects',elemMatch:{name:'zzz'}} //this is what I tried 
                                                     //but it doesn't work
  )}
 .exec(function(err,docs){
    //handle
  });

1 Answer 1

1

You can use match inside populate

.populate({
   path:'someVirtual',
   match: { objects: { $elemMatch: { name: 'zzz' } } },
   select: 'objects'                                        
})

and if you want to use projection then

.populate({
   path:'someVirtual',
   match: { objects: { $elemMatch: { name: 'zzz' } } },
   select: { objects: { $elemMatch: { name: 'zzz' } } }                                   
})
Sign up to request clarification or add additional context in comments.

1 Comment

It worked, thank you! This helped a lot, I tried reading the docs but I felt like the usage examples weren't clear. I hope they'd make it more detailed in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.