How can I execute a query using elemMatch in mongoose?

I am trying to query a user in my mongodb collection based on the following mongodb request:

db.users.find("boxes":{"$elemMatch":{"a":"foo","b":"bar"}})

This works if I request directly with mongodb. It returns any user who has a field with = "foo" and b = "bar".

How can I request this in mongoosejs? I tried using User.find().elemMatch , but it does not work. It looks like it is just projecting the results anyway. The original mongodb request really works for me, but I just need to replicate it in mongoosejs. Any ideas?

+7
mongoose
source share
2 answers

The documentation for elemMatch in mongoose is here .
I have not tested it, but it looks like you want to do

User.find().elemMatch("boxes", {"a":"foo","b":"bar"})

+8
source share

Tim's answer is correct, but if someone gets confused about what mongoose generates for requests on the mongo native api, I used this to understand what's outside

mongoose.set('debug', function (coll, method, query, doc) { console.log(coll + " " + method + " " + JSON.stringify(query) + " " + JSON.stringify(doc)); });

+2
source share

All Articles