Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elemMatch combined with other query fields in Mongoose

Sample data:

[{
    "_id": "529532bee0ea703842000003",
    "patientId": "123",
    "name": {
        "firstName": "John",
        "family": "Smith"
    },
    "diet": [{
        "_id": "1",
        "mealtType": "Break Fast",
        "timeofMeal": "2013-11-12T03:05:06.000Z",
        "status": "I",
        "calorie": {
            "value": 500,
            "unit": "cals"
        }
    },
    {
        "_id": "1",
        "mealtType": "Break Fast",
        "timeofMeal": "2013-11-12T03:05:06.000Z",
        "status": "A",
        "calorie": {
            "value": 550,
            "unit": "cals"
        }
    }]
}]

I wanted to fetch only active (status 'A') embedded document (diet document) for a given patientId ('123') using mongoose in node.

Here is my mongoose query:

query.where('patientId', 123)
     .where('diet').elemMatch(function(elem) {
    elem.where('_id', 1)
    elem.where('status', 'A')
})

Mongoose generated below query, which is brining all elements from embedded array diet for patient.

Mongoose: patients.find({ diet: { '$elemMatch': { _id: '1', status: 'A' } }, patientId: '123' })

The above query fetches all sub documents irrespective of status at Mongo Shell too.

They only way I could make it work at Mongo shell by wrapping each where condition {'patientId':'123'},{'diet' : { $elemMatch : {'status':'A'} }}.

db.patients.find({'patientId':'123'},{'diet' : { $elemMatch : {'status':'A'} }} ).pretty() // works fine 

How can I force Mongoose to enclose each query field in a curly braces or any other thoughts?

like image 920
user3067269 Avatar asked Dec 15 '22 03:12

user3067269


1 Answers

In your query that works, the $elemMatch object is not another query condition, but is the output field selection (i.e. projection) parameter to find.

To do the same in Mongoose, you'd do something like:

PatientsModel.find({patientId: '123'}, {diet: {$elemMatch: {'status': 'A'}}}, cb)

OR

PatientsModel
    .where('patientId', '123')
    .select({diet: {$elemMatch: {'status': 'A'}})
    .exec(cb);
like image 96
JohnnyHK Avatar answered Feb 05 '23 02:02

JohnnyHK