I have an API built with Node + Mongoose, and now I want to filter the data using some fields. Everything works fine, but how can I get the data like: 1 < age < 3 AND 8 < age < 11
I am trying this:
query.where('age').gte(1).lte(3);
query.where('age').gte(8).lte(11);
but this code only gets me 8 < age < 11
Thanks!
You mean $or, since an $and condition cannot possibly overlap where you condition would be true:
{
"$or": [
{ "age": { "$gte": 1, "$lte": 3 } },
{ "age": { "$gte": 8, "$lte": 11 } }
]
}
Also you are using JavaScript which has a nice free flowing object notation, so the helper methods are really overkill here. Use the standard query operator syntax instead.
Just a demo to show different forms of representing the same query:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var testSchema = new Schema({
"age": Number
});
var Test = mongoose.model( 'Test', testSchema, 'testcol' );
var query = Test.where({
"$or": [
{ "age": { "$gte": 1, "$lte": 3 } },
{ "age": { "$gte": 8, "$lte": 11 } }
]
});
console.log( JSON.stringify( query._conditions, undefined, 2 ) );
var query2 = Test.where().or([
{ "age": { "$gte": 1, "$lte": 3 } },
{ "age": { "$gte": 8, "$lte": 11 } }
]);
console.log( JSON.stringify( query2._conditions, undefined, 2 ) );
var query3 = Test.where().or(
[
Test.where("age").gte(1).lte(3)._conditions,
Test.where("age").gte(8).lte(11)._conditions
]
);
console.log( JSON.stringify( query3._conditions, undefined, 2 ) );
Which should also demonstrate that the "helpers" are not really adding much value to how the query is basically formed.