I have a Mongo query which returns the correct results in the Mongo console but when the same query is performed against a Mongoose model it returns an empty array.
It's the following line which isn't working as it should:
query.facilities = {$in: facilities.split(',')};
Declare my mongoose models
// places
placeSchema = mongoose.Schema({
name: String,
category: [{ type: Schema.Types.ObjectId, ref: 'categories' }],
facilities: [{ type: Schema.Types.ObjectId, ref: 'facilities' }],
});
Place = mongoose.model('places', placeSchema);
// categories
categorySchema = mongoose.Schema({
name: String,
slug: String
});
Category = mongoose.model('categories', categorySchema);
facilitiesSchema = mongoose.Schema({
name: String,
});
Facility = mongoose.model('facilities', facilitiesSchema);
My /places route
app.get('/places', function(req, res){
var geo = req.query.geo.split(',');
if(geo.length !== 2) {
handleError('valid_geo_coords_required');
}
var limit = typeof req.query.limit !== 'undefined' ? req.query.limit : 0;
var category = req.query.category;
var facilities = req.query.facilities;
var query = {
loc: {$near: geo}
};
if(typeof category !== 'undefined') {
query.category = category;
}
if(typeof facilities !== 'undefined') {
query.facilities = {$in: facilities.split(',')}; <---- this causes the problem
}
console.log(query); // pasting this into the mongo console returns correct results
Place.find(query).limit(limit).populate('category').populate('facilities').exec(function(err, data){
if (err) return handleError(err);
res.json(data);
});
});
The query object is:
{ loc: { '$near': [ '-3.188384', '55.94772' ] }, facilities: { '$in': [ '53012d6965b5e9a35efbb215' ] } }
This is the query I perform in the console:
db.places.find({ loc: { '$near': [ '-3.188384', '55.94772' ] }, facilities: { '$in': [ '53012d6965b5e9a35efbb215' ] } })
and returns a valid document.
Is there something specific to Mongoose which is affecting this?
Update
It seems to be this line that breaks it:
facilities: [{ type: Schema.Types.ObjectId, ref: 'facilities' }],
maybe because it's an array of objectId's?