Turistforeningen / node-mongo-querystring

Query builder for accepting URL query parameters into your MongoDB queries. Safe and feature rich. Supports most of MongoDB's query operators such as $eq, $gt, $lt, $ne, $in, $nin, $exists, $regex, geospatial queries such as bbox and near, as well as your own custom query business logic!
MIT License
100 stars 31 forks source link

Custom array query #40

Closed alexborisov closed 8 years ago

alexborisov commented 8 years ago

I want to create a custom query for an array. This is my structure:

{
  _id: 1234,
  assigned: {
    users: [{
      _id: 1111
    }]
  }
}

I expect that for this query

?assigned[]=1111&assigned[]=2222

I would write a function

function assigned(query, input) { // where input is [1111,2222]
  query['assigned.users._id'] = { $in: input }
}
Starefossen commented 8 years ago

Hi @alexborisov and thanks for using this library and submitting such a detailed ticket 😄

I have found, and fixed, two unrelated errors which would have prevented this kind of custom query from working correctly. I have also added a test for this make sure this works as intended in all future versions. With the new version 4.0.1 this custom function should work for you:

var qs = new MongoQS({
  custom: {
    assigned: function(query, input) {
      // make sure we handle normal string queries (?assigned=1111)
      if (typeof input === 'string') {
        input = input.split(',');
      }

      query['assigned.users._id'] = {
        // since query strings are strings we need to parse them to integers
        $in: inputValue.map(id => parseInt(id, 10))
      };
    }
  }
});
alexborisov commented 8 years ago

thank you! 👍