Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find documents that contain certain value for sub-object field Mongoose

Note: I asked this question here, however at that time I was working purely with MongoDB, now I am trying to implement this with Mongoose. I decided it was appropriate to ask a separate question as I believe the answer will be fundamentally different, however please let me know if I was incorrect in that decision.


I have a collection with the following format:

[ 
  {
     firstname: 'Joe',
     lastname: 'Blow',
     emails: [
       {
          email: '[email protected]',
          valid: false
       },
       {
          email: '[email protected]',
          valid: false
       }
     ],
     password: 'abc123',
     _id: 57017e173915101e0ad5d94a
  },
  {
     firstname: 'Johnny',
     lastname: 'Doe',
     emails: [
       {
          email: '[email protected]',
          valid: false
       }
     ],
     password: 'abc123',
     _id: 57017e173915101e0ad5d87b
  },
]

I am trying to find a user based on the emails.email field. Here is what I have so far:

UserModel.find()
         .where('emails')
         .elemMatch(function (elem) {
           elem.where('email').equals(userEmail);
         })
         .limit(1)
         .exec(
         (err, usersReturned) => {
           console.log('[email protected]');
         });

What am I doing wrong? I am new to Mongoose and just can't seem to figure this out.

like image 390
Leopold Joy Avatar asked Apr 04 '16 04:04

Leopold Joy


1 Answers

You could do something like this :

UserModel.find({"emails.email": userEmail}).limit(1).exec(function(err, user){
    if(err) console.log("Error: " + JSON.stringify(err));
    else if(user) console.log("User Returned is : " + JSON.stringify(user));
});
like image 77
SiddAjmera Avatar answered Nov 01 '22 20:11

SiddAjmera