Passing variables into a query in mongoose in the first argument

1.5k views Asked by At

I am using MEAN stack, i have an entry like this in my mongodb

{ "_id" : ObjectId("5577467683f4716018db19ed"),
"requestMatrix" : { "1698005072" : { "rideId" : "641719948", "status" :"accepted" },"1698005073" : { "rideId" : "641719545", "status" :"rejected" }  }, 
"partners":[ { "customerNumber" : 1698005072 }, { "customerNumber" : 1698072688 } ]}

I want to query the db to return me this entire document based on whether the status is accepted or rejected.

When I run the below query in a command prompt, i get the expected answer

db.joinedrides.find({'requestMatrix.1698005072.status':"accepted"})

But when i want to do the same from nodeJs, I am stuck as the number 1698005072 in the above query is a variable, i am not able to write a query for that.

tried something like this

var criteria = "'requestMatrix.'"+customerNumber+"'.status'";
    JoinedRide.find({criteria:"accepted"},function(err,joinedRides){

    })

where customerNumber will vary for different requests, in the above mentioned case its value is 1698005072

Any help is appreciated.

1

There are 1 answers

1
Yuri Zarubin On BEST ANSWER

You need to do something like this:

var query = {};
var criteria = "requestMatrix." + customerNumber + ".status";
query[criteria] = "accepted"

JoinedRide.find(query,function(err,joinedRides){

})