javascript - NodeJS MongoDB Dynamic Query -


i have nodejs server running express method @ '/api/jobs/'. when called querystring parameters url , make query against mongodb database jobs.

example url: '/api/jobs/?groups=1,2&statuses=3,4' 

the mongodb query trying construct this:

{ $or: [{"group.id" : 1}, {"group.id" : 2}], $or: [{"status.id": 3}, {"status.id": 4}]} 

if run directly against database results need can't think of way of constructing query dynamically in javascript. attempt i've made gives me object $or property can exist once in proper json object.

{$or : [{"group.id" : 1}, {"group.id" : 2}]} 

any ideas on how either using javascript or thorugh mongodb node api?

firstly query properties, strings:

const groupstring = req.query.groups; // === '1,2' const statusstring = req.query.statuses; // === '3,4' 

split @ commas , parse integers:

const groupnums = groupstring.split(',').map(parseint); // === [1, 2] const statusnums = statusstring.split(',').map(parseint); // === [3, 4] 

then search of group ids. query should this:

const query = {"group.id": { $in: groupnums }, "status.id": { $in: statusnums } }; 

do same status ids.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -