Let see the example below
I want to update just one record inside my ExpensesHouse so I build the following code
router.post("/editExpense/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
House.updateOne(
{ "expensesHouse._id": id },
{
$set: {
expensesHouse: {
_id: id,
expenseType: req.body.expenseType,
description: req.body.description,
price: req.body.price,
status: req.body.status,
userID: req.user.id
}
}
}
).then(house => {
req.flash("success_msg", "Expenses Updated");
res.redirect("/houses/dashboard");
});
});
It works fine and can update the record, but since I have 2 or more Objects all the others gone. So when I update let suppose 1: Object, expenseType: Water and I change the type of expense to other, the 0: Object just disappear and I need to update only the register with the _id: id
Below you can see the result after UpdateOne
Sky020
February 1, 2020, 2:52pm
2
Hello, corel.
Are you not potentially wanting to use findOneAndUpdate
?
findOneAndUpdate Docs
I hope this helps
Doing this way , returns me the same result.
router.post("/editExpense/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
House.findOneAndUpdate(
{ "expensesHouse._id": id },
{
$set: {
expensesHouse: {
_id: id,
expenseType: req.body.expenseType,
description: req.body.description,
price: req.body.price,
status: req.body.status,
userID: req.user.id
}
}
},
{ returnNewDocument: false }
).then(house => {
req.flash("success_msg", "Expenses Updated");
res.redirect("/houses/dashboard");
});
});
I got a solution. See below:
router.post("/editArquive/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
House.updateOne(
{ "expensesHouse._id": id },
{
$set: {
"expensesHouse.$._id": id,
"expensesHouse.$.expenseType": req.body.expenseType,
"expensesHouse.$.description": req.body.description,
"expensesHouse.$.price": req.body.price,
"expensesHouse.$.status": req.body.status,
"expensesHouse.$.userID": req.user.id
}
}
).then(house => {
req.flash("success_msg", "Expenses Updated");
res.redirect("/houses/arquiveExpense");
});
});
The problem are making a SET this way
$set: {
expensesHouse: {
_id: id,
expenseType: req.body.expenseType,
description: req.body.description,
price: req.body.price,
status: req.body.status,
userID: req.user.id
}
}
So I see the docs and change the way I show above and resolved.