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
Post a Comment