E
E
E2016-07-18 10:51:46
MongoDB
E, 2016-07-18 10:51:46

How to compose a mongodb query with an empty array?

Actually I try to make request on two fields. One of the fields receives an empty array. Finds nothing. How to do what would find? Or make this field optional?

var shops = [123, 345, 567];
var types = [];

{
      'shops': {
        $in: shops
      },
      'types':  {
        $in: types
      }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2016-07-18
@aylo

Build the query dynamically

var shops = [123, 345, 567];
var types = [];

var query = {};
if(shops.length) {
  query.shops = { $in: shops };
}
if(types.length) {
  query.types = { $in: types };
}

B
Bojczuk, 2016-07-18
@Bojczuk

If there is an initial array of all types, I would assign this value to var types if the type array that came from the source was empty, like this:

var types = types_from_source ? types_from_source : all_types

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question