如何在猫鼬中切换数组中的布尔值?

问题描述 投票:0回答:1

我想切换模式数组中的布尔值。 我正在尝试使用数据库中存在的值来切换值(请参阅代码)。但它只是把真变成假,而不是把假变成真。

代码如下

exports.postStatusItemchange = (req, res, next) => {
  const productId = req.body.productId;
  const itemId = req.body.itemId;
  
  Product.updateOne({_id: productId, "items._id": itemId}, {
    $set: {
      "items.$.status": !"items.$.status"
    }
  }).then((result) => {
    console.log(result);
    res.send("done");
  }).catch(err => {
    res.send(err);
  })
}

以下是供参考的架构

const productSchema = new Schema({
  name: {
    type: String,
    required: false,
  },
  status: {
    type: Boolean,
    required: false,
    default: true,
  },
  items: [
    {
      foodName: {
        type: String,
        required: true,
      },
      price: {
        type: Number,
        required: true,
      },
      status: {
        type: Boolean,
        default: true
      }
    },
  ],
});

我期望只要运行 API,状态字段中的值就会切换。谢谢你的时间。

node.js mongoose mongoose-schema
1个回答
0
投票

不幸的是,在这种情况下,位置运算符不会有太大帮助,您将不得不忙于

map
。这有它的缺点,因为它必须遍历 items 数组中的每个项目。另请注意,我正在使用
[{$set:{...}}]
那是因为从 Mongo 4.2 开始,您可以在 update 内聚合管道。

Product.updateOne({_id: productId}, 
[
  {
    $set: {
      items: {
        $map: {
          input: "$items",
          as: "i",
          in: {
            $cond: [
              { $eq: [ "$$i._id", itemId ] },
              { $mergeObjects: [ "$$i", { status: { $not: "$$i.status" } } ] },
              "$$i"
            ]
          }
        }
      }
    }
  }
]
)

游乐场

就是我的意思。如果要将

$set
与位置运算符一起使用,则需要传递一个显式值。否则,即使你写了一个条件,它也会用传递的任何条件对象更新字段。

© www.soinside.com 2019 - 2024. All rights reserved.