JBone JBone - 1 month ago 17
Node.js Question

dot notation params while searching mongo collection

I have a bit weird situation. The problem is that some of the parameters in

mongo
collection defined deep inside objects.

for example (my situation now). if I search by
id


db.collection.aggregate([{$match: {id: '1234567'}}])


so my
queryObj
looks like this in Node service side:

let queryObj = { $match: { id: customerId } };


but now there is another param
providerID
that I need to take into consideration to
aggregate


This is how it looks in Mongo query (and this runs fine):

db.getCollection('mydb').aggregate([{$match:{id:'31250044805', 'value.transactionDetail.medicalClaim.claimHeader.value.provider.providerNumber.providerID':'42344'}}])


How do I build my
queryObj
now in my Node.js service call?

I tried something like this:

if(providerId) {
queryObj['$match]'['value']['transactionDetail']['medicalClaim']['claimHeader']['value']['provider']['providerNumber']['providerID'] = providerID;
}


I also tried:

if(providerId) {
queryObj.$match.value.transactionDetail.medicalClaim.claimHeader.value.provider.providerNumber.providerID = providerID;
}


but it fails because I am referencing params on
undefined
values in the chain.

Any suggestions?

Answer

You can use Object.assign to add props to an object.

let queryObj = { $match: { id: customerId } };
if(providerId) {
  Object.assign(queryObj.$match, {'value.transactionDetail.medicalClaim.claimHeader.value.provider.providerNumber.providerID': '1234'});
}

Or, simply by using bracket notation:

queryObj.$match['value.transactionDetail.medicalClaim.claimHeader.value.provider.providerNumber.providerID'] = '1234';
Comments