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

Correct way to update and handle input values in custom function #62

Closed kcfgl closed 7 years ago

kcfgl commented 7 years ago

First of all, awesome library so thank you. I'm struggling just a bit however and likely doing something dumb.

Part of my final query will need to do an $elemMatch. I didn't see this option in the docs so I figured custom function. The final structure of this piece of the mongo query should be: place_amentities: {'$elemMatch': {lounge: 1, restrooms: 1}}

The params in the URL would be ?pa=lounge,restrooms

Pretty straightforward custom function: pa: function(query, input) { const amentitiesArr = input.split(',').map(a => a +':'+1); query['place_amentities'] = { $elemMatch: amentitiesArr }; }

The issue I'm having is that final output looks like this: place_amentities: { '$elemMatch': [ 'lounge:1', 'restrooms:1'] }

Instead of this: place_amentities: { '$elemMatch': { lounge: 1, restrooms: 1} }

Everything seems to be a string. The core library doesn't do that though, everything is created exactly as Mongo would expect it, so I'm sure I'm just screwing up something simple in the custom function.

Thanks for any help you can provide. I know this isn't an "issue" but maybe others have run into the same question.

Starefossen commented 7 years ago

Try the following:

pa: function(query, input) { 
  const amentitiesArr = input.split(',').map(a => { [a]: 1 }); 
  query['place_amentities'] = { $elemMatch: amentitiesArr }; }
}
kcfgl commented 7 years ago

Works great, thank you!