1

I'm trying to make a 'like' route that find user by _id then query inside user.post an object id, so far I tried this:

User.find({
    "_id": logged_user,
    "posts_id": {
        $elemMatch: req.body.id
    }
}, (err, data) => {
    if (err) {
        res.json(err)
    }
    console.log(data);
})

Schema:

 username: String,
 posts:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
 }]

it returns an empty array '[]', how can I return true of false if it exists?

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Bruno Henrique
  • 131
  • 4
  • 11

1 Answers1

3

You are using $elemMatch wrong. It needs an object. Do it this way:

User.find({"_id":logged_user,"posts":{$elemMatch: {$eq : req.body.id}}},(err,data)=>{ 

if(err){
res.json(err)
}
console.log(data);
)
Kamesh
  • 1,122
  • 9
  • 12
  • it works with $eq thank you ! – Bruno Henrique Jul 29 '17 at 11:12
  • 1
    Welcome :) $eq is for checking if the objects are equal. You can use more operators like $gt, $lt. Read the documentation for more: https://docs.mongodb.com/manual/reference/operator/query/elemMatch/ – Kamesh Jul 29 '17 at 11:14
  • 1
    @BrunoHenrique Or more to the point is `$elemMatch` is not required here at all. That operator need only be used when matching "multiple criteria" for an array element. All you need have issued here is `.find({ "_id": logged_user, "posts": req.body.id }, ...` since you have only **one** criterion for the array element. So `$elemMatch` is completely unessary, and sadly quite misunderstood. But it actually is explained in the documentation, as well as many existing "correct" answers here. – Neil Lunn Jul 29 '17 at 13:12