I want to return a restaurant with given shortName
and filter its array menuEntries
to only contain menu entries with field isAvailable
set to true
.
Here is my schema:
var restaurantSchema = new mongoose.Schema({
shortName: String,
fullName: String,
address: String,
logoImageUrl: String,
description: String,
location: {
type: { type: String },
coordinates: [Number]
},
menuEntries: [{
name: String,
description: String,
isAvailable: Boolean
}],
updatedAt: {type : Date}
});
restaurantSchema.index({ 'location': '2dsphere' });
mongoose.model('Restaurant', restaurantSchema, 'Restaurants');
I am using the following query but it still returns menu entries that have isAvailable
set to false
:
Restaurant
.findOne({
shortName: shortName,
menuEntries: { $elemMatch: { isAvailable: { $eq: true } } }
}, function(error, restaurant) {
if (error) {
returnJsonResponse(response, 500, {
'message': error
});
} else if (!restaurant) {
returnJsonResponse(response, 404, {
'message': 'Restaurant with name ' + shortName + ' doesn\'t exist'
});
} else {
returnJsonResponse(response, 200, restaurant);
}
});
EDIT
It doesn't work with the following code either:
Restaurant
.findOne({
shortName: shortName
})
.elemMatch('menuEntries', {'isAvailable': true})
.exec(function(error, restaurant) {
if (error) {
returnJsonResponse(response, 500, {
'message': error
});
} else if (!restaurant) {
returnJsonResponse(response, 404, {
'message': 'Restaurant with name ' + shortName + ' doesn\'t exist'
});
} else {
returnJsonResponse(response, 200, restaurant);
}
});
I am using mongoose ^5.6.2 and MongoDB 3.6.9. What am I doing wrong?