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

Filtering string fields will not work when filter value consists of numbers #71

Open Halt001 opened 7 years ago

Halt001 commented 7 years ago

qs.parse({"foo":">1"}) results in{"foo":{"$gt":1}} and not{"foo":{"$gt":"1"}} where the '1' is converted to a Number field automatically. If the foo field is a string field in the database than this search query will find nothing.

I haven't tested it but this will probably also be true for booleans. So you probably can't filter a text field on the word 'true'.

There should be a way to force the creation of a string filter for values that could also be a number or a boolean.

Starefossen commented 7 years ago

That is correct behaviour with the default settings. You can turn off automatic parsing of Numbers and Booleans by setting toNumber and toBoolean respectively to false like this:

const qs = new MongoQS({
  string: {
    toNumber: false,
    toBoolean: false,
  }
});
Halt001 commented 7 years ago

Sorry fo the late reply. This doesn't help the situation where you want to combine a filter on a number field and a string field like this: qs.parse({"fooString":">1", "fooNumber":">1"}); where you expect: {"fooString":{"$gt":"1"}, "fooNumber":{"$gt":1}}

Maybe it would help if you add single quotes to the syntax to aid in discriminating string fields from number fields. Like this: qs.parse({"fooString":">'1'", "fooNumber":">1"}); This may need to be escaped on the url though.