I’m working on the nightlife coordination app and I can’t seem to update an array of objects. I want to update some properties on a particular object and then save it, but when I check the database, it doesn’t show that it has been updated.
Here is my model, and my server code:
The database query is at the very end of the server code. I did business.save() before but it threw an error saying that I can’t use the save function with $elemMatch, and to use “Model.update()” instead. I’ve reached a very tough obstacle, and have been trying to solve this issue all day. If someone can help, I would greatly appreciate it.
Couldn’t crack $elemMatch, do I decided to do a workaround:
app.post("/add-bar", jsonParser, (req, res) => {
List.findOne(
{location: req.body.data.location, query: req.body.data.query},
(err, business) => {
if (err) {
throw err;
}
else {
// Find index of the array containing the name of location
let ind = -1;
for (let i in business.list) {
if (business.list[i].name === req.body.data.name) {
ind = i;
break;
}
}
// Didn't find a name. Return with status 400.
if (!~ind) return res.status(400).send();
if (business.list[ind].users.indexOf(req.body.data.username) !== -1) {
res.json({data: "Exists"});
}
else {
business.list[ind].attendance++;
business.list[ind].users.push(req.body.data.username);
business.markModified("list");
business.save()
res.send();
}
}
})
})
I will give this a try, thank you so much! Before trying $elemMatch, I had tried using .forEach to match the name, but in hindsight that wouldn’t have worked anyway.