node.js - One-liner $in nullification MongoDB -
the idea make request (in js) fetch documents field being contained in given array if array defined, or documents if array not defined.
i wondered if there elegant mean give $in argument parameter nullifies behavior, can used one-liner. take idea have make kind of conditional request more elegant.
here snippet using mongoose:
let query = somemodel.find(); if (somearray) { query = query.where(somefield).in(somearray); } query.exec();
sure works, requires store query in variable, not cool.
aggregation might help.
let itemvalues = somearray || []; somemodel.aggregate([ { $match: { "somefield": { [itemvalues.length > 0 ? "$in" : "$nin"]: itemvalues} } } ]).exec()
Comments
Post a Comment