【问题标题】:Checking existed value in array of nested object before update in Mongoose在 Mongoose 更新之前检查嵌套对象数组中的现有值
【发布时间】:2021-11-28 06:36:00
【问题描述】:

这是我的购物车模型:

const cartSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "userSchema",
    },
    cart: [
        {
            product: { type: mongoose.Schema.Types.ObjectId, ref: "productSchema" },
            amount: { type: Number, require: true, min: 0 },
            price: { type: Number, min: 0 },
        },
    ],
    totalPrice: {
        type: Number,
        min: 0,
        default: 0,
    },
});

我想在更新之前检查 cart.product,如果不存在则推送新商品,否则会随商品增加金额 我正在尝试这种方式先测试推送,但它无法正常工作

router.put("/add-to-cart", authenticateToken, async (req, res) => {
    try {
        const productInfo = await productSchema.findById(req.body.id);
        const filter = {
            $and: [{ user: req.user }, { "cart.product": { $nin: [req.body.id] } }],
        };
        const options = { upsert: true, new: true, setDefaultsOnInsert: true };
        const update = {
            $push: {
                cart: {
                    product: req.body.id,
                    amount: req.body.amount,
                    price: req.body.amount * productInfo.productPrice,
                },
            },
        };
        await cartSchema.findOneAndUpdate(filter, update, options);
        return res.status(201).send({ status: true });
    } catch (err) {
        res.status(500).send({ message: err });
    }
});

【问题讨论】:

    标签: mongodb express mongoose mongodb-query mongoose-schema


    【解决方案1】:

    我认为您的代码运行良好,可能是因为您的 Id 和 objectId 转换

    db.collection.update({
      $and: [
        {
          user: "1"
        },
        {
          "cart.product": {
            $nin: [
              "1"
            ]
          }
        }
      ],
      
    },
    {
      $push: {
        cart: {
          product: "1",
          amount: 1,
          price: 10
        }
      }
    })
    

    mongoplayground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 2023-01-18
      • 1970-01-01
      • 2021-01-04
      相关资源
      最近更新 更多