Split the string and convert to json object using nodejs

162 Views Asked by At

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?

1

There are 1 best solutions below

1
Harish On

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)