0

I am trying to filter my data(mongoDB) based on the query params which I will be sending in the api as below. But mongoDB doesn't support comparison symbols so I am trying to convert all the symbols to proper query operators before sending to find().

GET /companies/?created_by<2&type<=Subsidiary&modified_by!=3

For my above url req.query will look like below:

{ 'created_by>2': '', // { created_by: { $gt: 2} }
  'type<': 'Subsidiary', // { type: { $lte: Subsidiary } }
  'modified_by!': '3' }  //  { modified_by: { $ne: 3 } }

I have six cases while filtering. Whenever particular field of my data comes for filtering I have to convert it proper json.

field=value // { <field>: { $eq: <value> } }
field!=value  // { <field>: { $ne: <value> } }
field<value   // { <field>: { $lt: <value> } }
field>value   // { <field>: { $gt: <value> } }
field<=value  // { <field>: { $lte: <value> } }
field>=value  // { <field>: { $gte: <value> } }

Below is my json object of two fields(this object may change based on my filtering):

{ 
   'created_by>2': '',
   'type<': 'Subsidiary'
}

I want to convert the above json to below format with nodejs query parameters ($gt,$lte).

{ 
   created_by: { '$gt': '2' }, 
   type: { '$lte': 'Subsidiary' } 
}

How to convert using nodejs?

5
  • What problem are you having in doing this? Can you include the code you have already tried? Commented Jul 1, 2019 at 4:57
  • Which type of format you want as result? For example, json etc. Commented Jul 1, 2019 at 4:59
  • are there any other combinations? Commented Jul 1, 2019 at 5:01
  • You don't need to specify all operands, if you accept "min" and "max" parameters you can do exactly the same with way less code, e.g. "field < value" means "max=value&min=0" Commented Jul 1, 2019 at 6:41
  • I didn't get your point. Can u give sample url how can I pass my query params Commented Jul 1, 2019 at 7:36

1 Answer 1

2

you can try something like below,

var obj= { 
   'created_by>2': '',
   'type<': 'Subsidiary'
}

var result = Object.keys(obj).reduce((acc, el)=> {
var op = ''
if(el.indexOf('>') > -1) {
    op = '>'
} else {
    op ='<'
}
var elCopy = el.split(op)
//console.log(el);

acc[elCopy[0]] = { [op === '>' ? '$gt' : '$lte' ]: elCopy[1] ? elCopy[1] : obj[el] }
return acc;
}, {})

console.log(result)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You Harish. This will not give complete solution for my requirement I updated my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.