簡體   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