繁体   English   中英

如何更新Mongo文档数组内的对象(在特定索引处)

[英]How to update an object inside a Mongo Document Array (at a specific index)

我想让用户检查他们是否“购买”了食品杂货并更新了数据库。

具体来说,当用户选中一个框时,我想切换在对象对象上acquired的布尔属性。 成分存储在GroceryList文档上的数组中:

这是杂货清单的架构

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 },
}

成分看起来像这样:

{ quantity: '3',
  unit: null,
  ingredient: 'zucchinis, chopped',
  minQty: '3',
  maxQty: '3',
  acquired: false }

我看过很多类似的问题,Mongoose文档和MongoDB文档,我尝试了很多不同的版本,但是我很困惑。

前端:

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

后端:

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

结果/问题:当我运行上面的代码时,我成功地看到1种成分的acquired属性在回调中从false > true切换

console.log(updatedList.ingredients);

但是,下一次我获取食品杂货清单时,该成分已acquired = false 这使我相信GroceryList文档实际上并没有在数据库中得到更新。 我该如何解决?

如果直接使用数组索引修改数组元素,猫鼬将无法跟踪数组内部的变化

尝试在保存之前添加此行

groceryList.markModified(`ingredients.${ingrIdx}.acquired`);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM