JBone JBone - 1 year ago 84
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

collection defined deep inside objects.

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

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

so my
looks like this in Node service side:

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

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

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
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
values in the chain.

Any suggestions?

Answer Source

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';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download