gpt4 book ai didi

javascript - UpdateOne mongodb 而不更改其他对象

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:05 26 4
gpt4 key购买 nike

看下面的例子

MongoDB Schema

我只想更新 ExpensesHouse 中的一条记录,因此我构建了以下代码

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");
});
});

它工作正常并且可以更新记录,但由于我有 2 个或更多对象,所以其他对象都消失了。因此,当我更新时,假设 1: 对象,费用类型:水,然后我将费用类型更改为其他,0: 对象就消失了,我只需要使用 _id: id 更新寄存器

下面可以看到UpdateOne之后的结果

MongoDB Afeer Update

最佳答案

试试这个:

router.post("/editExpense/:houseId/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
var houseId : mongoose.Types.ObjectId(req.params.houseId);
House.updateOne(
{ "_id": houseID, "expensesHouse._id": id },
{
$set: {
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/dashboard");
});
});

关于javascript - UpdateOne mongodb 而不更改其他对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com