Mongoose - 如何通过另一个字段的值增加一个字段

时间:2021-03-29 08:29:57

标签: mongodb mongoose

我是猫鼬 ODM 的新手。我试图通过另一个字段的值增加一个值。以下是我尝试过的:


const deletedCartItem = await Cart.findOneAndUpdate(
    { sessionId: req.session.sessionId, "productInfo.productId": product_id },
    {
      $inc: {
        checkoutAmount: "$productInfo.totalAmount"//totalAmount is a nested field here.
      },
      $pull: {
        productInfo: { productId: product_id },
      },
    },
    { new: true, useFindAndModify: false }
  );


我的收藏的架构如下:


const cartSchema = mongoose.Schema({
  sessionId: {
    type: String,
    unique: true,
  },

  checkoutAmount: {
    type: Number,
  },

  orderStatus: {
      type: String,
      default: "INCART"
  },

  productInfo: [
    {
      productId: {
        type: String,
        required: true,
        unique: true,
      },
      quantity: {
        type: Number,
        required: true,
      },
      price: {
        type: Number,
      },
      totalAmount: {
        type: Number,
      }
    }
  ],
});

我得到的错误是 - enter image description here

我在这里遗漏了什么吗? 提前致谢!

1 个答案:

答案 0 :(得分:1)

更新不允许将内部字段的值用于其他字段,您必须从 MongoDB 4.2 开始使用 update with aggregation pipeline

  • $reduce 迭代 productInfo 的外观并检查条件是否 productId 匹配,然后返回其 totalAmount
  • $add 使用从上面的 checkoutAmount 操作返回的 totalAmount 来增加 $reduce
  • $filter 迭代 productInfo 的循环并过滤没有匹配 productId 的元素
const deletedCartItem = await Cart.findOneAndUpdate(
  { sessionId: req.session.sessionId, "productInfo.productId": product_id },
  [{
    $set: {
      checkoutAmount: {
        $add: [
          "$checkoutAmount",
          {
            $reduce: {
              input: "$productInfo",
              initialValue: 0,
              in: {
                $cond: [
                  { $eq: ["$$this.productId", product_id] },
                  "$$this.totalAmount",
                  "$$value"
                ]
              }
            }
          }
        ]
      },
      productInfo: {
        $filter: {
          input: "$productInfo",
          cond: { $ne: ["$$this.productId", product_id] }
        }
      }
    }
  }],
  { new: true, useFindAndModify: false }
);

Playground