[英]How to update an object inside a Mongo Document Array (at a specific index)
I want to let a user check off whether they've "acquired" a grocery item and update the Database. 我想让用户检查他们是否“购买”了食品杂货并更新了数据库。
In more concrete terms, when a user checks a box, I want to toggle a Boolean property acquired
on an ingredient object. 具体来说,当用户选中一个框时,我想切换在对象对象上
acquired
的布尔属性。 Ingredients are stored in an array on the GroceryList
document: 成分存储在
GroceryList
文档上的数组中:
Here is the Schema for a Grocery List 这是杂货清单的架构
const GroceryListSchema = mongoose.Schema({
createdAt : { type: Date, default: Date.now },
updatedAt : { type: Date },
ingredients : { type: Array },
recipes : { type: Array },
user : { type: mongoose.Schema.Types.ObjectId, ref: 'UserSchema', required: true },
}
An ingredient looks like this: 成分看起来像这样:
{ quantity: '3',
unit: null,
ingredient: 'zucchinis, chopped',
minQty: '3',
maxQty: '3',
acquired: false }
I've looked at a lot of similar questions, the Mongoose documentation and the MongoDB documentation and I've tried a ton of different versions but I'm stumped. 我看过很多类似的问题,Mongoose文档和MongoDB文档,我尝试了很多不同的版本,但是我很困惑。
Frontend: 前端:
function toggleIngredient(elmt, groceryListId, ingrIdx) {
$.post('/cart/grocery-list/toggleIngredient', {
groceryListId,
ingrIdx,
newValue: elmt.checked, // if checkbox was checked before toggling it
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}
Backend: 后端:
app.post('/cart/grocery-list/toggleIngredient', (req, res, next) => {
const { groceryListId, ingrIdx, newValue } = req.body;
GroceryListSchema.findById(groceryListId, (err, groceryList) => {
if (err) return next(err);
// if was unchecked, change to checked & vice-versa
groceryList.ingredients[ingrIdx].acquired = newValue;
// save updated grocery list
groceryList.save().then((updatedList) => {
console.log(updatedList.ingredients);
}).catch(error => next(error));
});
});
RESULTS / THE PROBLEM: When I run the code above, I successfully see 1 ingredient's acquired
property get toggled from false
-> true
in the callback 结果/问题:当我运行上面的代码时,我成功地看到1种成分的
acquired
属性在回调中从false
> true
切换
console.log(updatedList.ingredients);
However, the next time I fetch the grocery list, that same ingredient's acquired = false
. 但是,下一次我获取食品杂货清单时,该成分已
acquired = false
。 This leads me to believe that the GroceryList
document isn't actually getting updated in the database. 这使我相信
GroceryList
文档实际上并没有在数据库中得到更新。 How do I fix this? 我该如何解决?
mongoose can't track changes inside the array if you modify array element directly using its index 如果直接使用数组索引修改数组元素,猫鼬将无法跟踪数组内部的变化
try adding this line before saving 尝试在保存之前添加此行
groceryList.markModified(`ingredients.${ingrIdx}.acquired`);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.