Reputation: 1183
I have a function in Express and NodeJS where I can switch a Boolean value of an Item. So when the function is called the Boolean will be swapped to the other value. I do a console.log of Boolean. The object inside my MongoDB doesn't get updated. I have a Post, Get and GetAll request of the same objects to and from the MongoDB and they all work. So there is no problem with the connection to the database.
router.post("/payed/:id", (req, res) => {
Item.findOne({ _id: req.params.id }, (err, item) => {
item.childeren.forEach((child) => {
if (child.name === req.body.name) {
console.log(child.payed);
child.payed = !child.payed;
console.log(child.payed);
}
});
item.save((saveErr, saveItem) => {
if (saveErr) res.send(saveErr);
return res.status(200).send(saveItem);
});
});
});
Upvotes: 1
Views: 95
Reputation: 3254
.save()
in mongoose is used to save a new document. You can use findOneAndUpdate
to update the record after fetching it. Try something like this:
router.post("/payed/:id", (req, res) => {
Item.findOne({ _id: req.params.id }, (err, item) => {
/* get children */
let children = item.children;
/* updating children's array */
children.forEach((child) => {
if (child.name === req.body.name) {
child.payed = !child.payed;
}
});
/* resaving the document */
Item.findOneAndUpdate({ _id: req.params.id },
{children: children },
{new: true},
(saveErr, updatedDoc) => {
if (saveErr) res.send(saveErr);
return res.status(200).send(updatedDoc);
});
});
});
Upvotes: 1