简体   繁体   中英

NodeJS MongoDB Dynamic Query

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM