【问题标题】:I want to remove the property inside a object in mongodb我想删除 mongodb 中对象内的属性
【发布时间】:2019-03-10 21:59:28
【问题描述】:

我在一个集合中有这个 bson 文档。我想根据动态值删除一个键。

{
  "_id": ObjectId("53ccff9bbb25567911f208a2"),
  "image": {
    "image1": "5213423424234.jpg",
    "image2": "5213423424235.jpg",
    "image3": "5213423424236.jpg"
  }
}

应要求我会得到“image1”

temp/5bb3685b663c6f001d14c5da/dl/image1

我将密钥保存在变量中

let keyid = req.params.k_id

如果我直接调用密钥,这可行。

  let qry = {
    _id: mongojs.ObjectId(req.params.p_id)
  }
  let update = {
    $unset: {
      "image.image1": ""
    }
  }

  db.inventory.findAndModify({
      query: qry,
      update: update,
      safe: true
    }, function (err, doc) {
        if (err) {
          res.status(500).json({
            "success": false,
            "error": err
          })
          return
        }

        res.status(200).json({
          "success": true,
          "message": "Deleted image key"
        })
        return
    })

但由于关键是动态的,我无法找到具有各种可能性的解决方案

// Try1
    $unset: {
      'image.' + keyid: ""
    },
// Try2
    $unset: {
      `image.${keyid}`: ""
    }

【问题讨论】:

    标签: javascript node.js mongodb express object


    【解决方案1】:

    您可以尝试像这样更改更新obj

    let update = {}
    update["$unset"] = {};
    update["$unset"]['image.' + keyid] = '';
    

    【讨论】:

      【解决方案2】:

      您需要以编程方式构建您的 $unset 对象:

      这个问题在这里得到了回答:using a variable in mongodb update

      【讨论】:

        猜你喜欢
        • 2016-08-28
        • 1970-01-01
        • 2022-07-12
        • 1970-01-01
        • 2021-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-17
        相关资源
        最近更新 更多