Reputation:
I'm having real trouble with MongoDB and Mongoose queries. The thing is, I have this Menu
schema:
var menuSchema = new Schema({
userID: String,
name: String,
meals: [{
day: Number,
hour: Number,
minute: Number,
aliments: [{
name: String,
amount: Number,
}],
}],
});
So I'd like to know how to get a specific meal or aliment and how to update them throught the _id
value, automatically generated when I add them.
Thank you so much.
David.
Upvotes: 0
Views: 162
Reputation:
I finally could get it working for meals, but not for aliments. I'm doing this for meals:
Menu.update({_id: request.params.menu_id, 'meals._id': request.params.meal_id}, {'meals.$.hour': request.body.hour)}, function(error, affected, raw) {
response.send(error);
});
And this for aliments:
Menu.update({_id: request.params.menu_id, 'meals.aliments._id': request.params.aliment_id}, {'meals.aliments.$': {name: request.body.name, amount: request.body.amount}}, function(error, affected, raw) {
response.send(error);
});
EDIT: ok so I looked for an answer on other posts and I found out the solution.
Looks like the $ positional operator does NOT work with multi-level arrays. Actually, it works only for 1-level arrays (that's why it works for meals but it doesn't for aliments).
So I guess the solution is splitting meals or aliments in documents and reference them with a mealID or alimentID.
I hope they add multi-level positional operator soon. It would be great.
Upvotes: 2