Friday 14 April 2017

One-liner $in nullification MongoDB

The idea is to make a request (in JS) that fetch documents with a field being contained in a given array if the array is defined, or all documents if the array is not defined.

I just wondered if there is any elegant mean to give the $in argument a parameter that nullifies its behavior, that can be used as an one-liner. I take any idea you have to make this kind of conditional request more elegant.

Here is a snippet using Mongoose:

let query = SomeModel.find();
if (someArray) {
    query = query.where(someField).in(someArray);
}
query.exec();

Sure it works, but it requires to store the query in a variable, so not so cool.



via Cobaltway

No comments:

Post a Comment