【问题标题】:nodejs / mongoDb: update many fields in one requestnodejs / mongoDb:在一个请求中更新许多字段
【发布时间】:2021-08-07 01:15:07
【问题描述】:

如何更新多个 orderStatus 而不是只更新一个?

request.body.type默认为字符串,只包含一种类型;

isCompleted 的类型变为真时,我什至想要之前的枚举索引 isCompleted 变为真

有可能还是我需要在前端进行修改?

这里是代码

const orderSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    orderStatus: [
      {
        type: {
          type: String,
          enum: ["ordered", "packed", "shipped", "delivered"],
          default: "ordered",
        },
        date: {
          type: Date,
        },
        isCompleted: {
          type: Boolean,
          default: false,
        },
      },
    ],
  }
exports.updateOrder = (req, res) => {
  Order.updateOne(
    { _id: req.body.orderId, "orderStatus.type": req.body.type },
    {
      $set: {
        "orderStatus.$": [
          { type: req.body.type, date: new Date(), isCompleted: true },
        ],
      },
    }
  ).exec((error, order) => {

【问题讨论】:

  • 您是否尝试过更新数组过滤器?
  • 我在哪里可以将数组过滤器放在 updateOrder 中?

标签: node.js reactjs mongodb mongoose react-redux


【解决方案1】:

嘿,你可以使用 updateMany() 操作

db.collection.updateMany(
   <query>,
   { $set: { status: "D" }, $inc: { quantity: 2 } },
   ...
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 2020-09-24
    • 2011-08-26
    • 1970-01-01
    • 2022-08-24
    • 1970-01-01
    • 2018-07-29
    • 2018-08-03
    相关资源
    最近更新 更多