2

I have a NodeJS server running express with a get method at '/api/jobs/'. When called I get some querystring parameters from the url and they make a query against the MongoDB database to get jobs.

Example Url: '/api/jobs/?Groups=1,2&Statuses=3,4'

The MongoDB query i am trying to construct is this:

{ $or: [{"Group.Id" : 1}, {"Group.Id" : 2}], $or: [{"Status.Id": 3}, {"Status.Id": 4}]}

If I run this directly against the database I get the results I need but I can't think of way of constructing the query dynamically in JavaScript. Any attempt i've made gives me an object like this as the $or property can only exist once in a proper JSON object.

{$or : [{"Group.Id" : 1}, {"Group.Id" : 2}]}

Any ideas on how to do this either using JavaScript or thorugh the MongoDB Node API?

2 Answers 2

2

Firstly get the query properties, which will be strings:

const groupString = req.query.Groups; // === '1,2'
const statusString = req.query.Statuses; // === '3,4'

Split at the commas and parse as integers:

const groupNums = groupString.split(',').map(parseInt); // === [1, 2]
const statusNums = statusString.split(',').map(parseInt); // === [3, 4]

Then search for any of the group IDs. Your query should look like this:

const query = {"Group.Id": { $in: groupNums }, "Status.Id": { $in: statusNums } };

Do the same for the status IDs.

Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Thanks
0

You can use this

app.get('/', function(req, res, next) {
var queryArry = [];
for (var i in req.query) {
    var sampleObject = { value: [] };
    sampleObject.name = i;
    req.query[i].split(',').forEach(function(each) {
        sampleObject.value.push(parseInt(each));
    })
    queryArry.push(sampleObject);
 }
  var mongoquery = {};

  for (var i in queryArry) {

     mongoquery[queryArry[i].name] = queryArry[i].value;

 }
  res.send(mongoquery);
 });

But in this case, you have to send same name field of MongoDB and query parameter key. If you did this it is fully dynamic query builder.

Comments

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.