Rohan Kumar
Rohan Kumar

Reputation: 67

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.

Upvotes: 0

Views: 290

Answers (1)

Karl L
Karl L

Reputation: 1725

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 );
});

Upvotes: 1

Related Questions