Search code examples
mongoosesubdocument

Mongoose findOne Returning all sub documents


I tried retrieving only one subdocument from the collection. But it is all subdocuments, even those which do not match the filter.

LevelXP.findOne({
            'guild':"715192953118654467",
            'users.user': "687893451534106669"
        },(err,result)=>{
            if(err) throw err;
            console.log(result.users)
          }
})
This is the data I have

But when I use the above code it returns all subdocuments when I should return only 1. Please help.


Solution

  • You may want to use a position operator $ (reference link here). To make your query projection to just return sub-document which matches

    So in your case, you can do this:

    LevelXP.findOne({
                'guild':"715192953118654467",
                'users.user': "687893451534106669"
               },
               "users.$",
              (err,result)=>{
                console.log( result );
    });
    

    or, a variation of the syntax (paired), like this:

    LevelXP.findOne({
                'guild':"715192953118654467",
                'users.user': "687893451534106669"
               },
               {"users.$":1},
               (err,result)=>{
                console.log( result );
    });