mongodb - Mongoose 查询使用 if else possible?

标签 mongodb mongoose mongodb-query

我有这个架构:

const guestSchema = new Schema({
  id: String,
  cart: [
    {
      product: {
        type: mongoose.Schema.ObjectId,
        ref: "products"
      },
      quantity: Number
    }
  ]
});

我有这个问题:

Guest.findOneAndUpdate(
        { id: req.sessionID },
        {
          $cond: [
            { "cart.product": { $ne: req.body.itemID } },
            { $push: { "cart": { product: req.body.itemID, quantity: 1 } } },
            { $inc: { "cart.quantity": 1 } }
          ]
        },
        { upsert: true, new: true }
      ).exec(function(err, docs) {
        err ? console.log(err) : res.send(docs);
});

基本上,我要做的是根据条件进行更新。我尝试使用 $cond,但发现该运算符并不像我正在做的那样用于查询。

基于此:

{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }

我的查询需要类似于此运算符功能的东西。

让我们分解一下我的情况:

对于我的 bool 表达式:我想检查 req.body.itemID 是否是 $ne 我购物车中的任何值

如果为 true,则:$push 将 itemID 和数量放入购物车

否则(那么项目已经存在):$inc 数量加 1

问题:如何实现这个结果?我需要进行两个单独的查询吗?如果可能的话,我尽量避免这样做

最佳答案

我浏览了他们所有的 Update Field Operators ,并且可能无法按照我想要的方式执行此操作。

我想知道为什么更新操作符没有$cond。尽管如此,我已经找到了我希望功能完成的解决方案。只是不是我喜欢的优雅时尚。

Guest.findOneAndUpdate(
        { id: req.sessionID },
        { id: req.sessionID }, //This is here in case need to upsert new guest
        { upsert: true, new: true }
      ).exec(function(err, docs) {
        if (err) {
          console.log(err);
        } else {

          //Find the index of the item in my cart
          //Returns (-1) if not found
          const item = doc.cart.findIndex(
            item => item.product == req.body.itemID
          );

          if (item !== -1) {
            //Item found, so increment quantity by 1
            doc.cart[item].quantity += 1;
          } else {
            //Item not found, so push into cart array
            doc.cart.push({ product: req.body.itemID, quantity: 1 });
          }

          doc.save();
        }
});

关于mongodb - Mongoose 查询使用 if else possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49449179/

相关文章:

mongodb - 在 MongoDB 中展开查找操作的结果时丢失记录

node.js - Mongoose 错误 : You can not `mongoose.connect()` multiple times while connected

javascript - Mongoose 在嵌套数组上运行 Get

python - 在 MongoDB 中重用 Cursor 对象

java - MongoDB Change Stream读取旧更新数据

javascript - Mongoose 查询以提取每个对话的最新文档

spring - 包括 near 和 textcriteri 在内的多个标准在 spring data mongodb 中不起作用

javascript - Mongoose 发现有冲突的日期

node.js - mongoosejs findByIdAndUpdate 最好的方法

node.js - 如何使用 Mongoose 在 mongoDB 中填充 3 个集合