【问题标题】:Update one item of an array which is a property of an object in mongodb and nodejs更新数组的一项,它是 mongodb 和 nodejs 中对象的属性
【发布时间】:2020-07-10 16:00:30
【问题描述】:

您好,我正在尝试使用 nodejs 更新 mongodb 中的单个数组项。我在 mongodb 中的数据结构是这样的:

{
    "_id": "5e818db59cedd232d83c66cb",
    "project": "projectX",
    "version": 1,
    "salesChannel": "channel42",
    "country": "Austria",
    "book": true,
    "categories": [
      {
        "pieceItems": [
          {
            "category": "pieceItems",
            "identifier": "1.1",
            "registrationHints": "Scan the barcode OR register the itemNumber manually",
            "variant": "Tax-Group 19%",
            "additionalHints": "optionally provided"
          }
        ],
      },
      {
        "weightItems": [
          {
            "category": "weightItems",
            "identifier": "2.1",
            "registrationHints": "Scan the barcode OR register the itemNumber manually",
            "variant": "Tax-Group 19%",
            "additionalHints": "optionally provided"
          },
          {
            "category": "weightItems",
            "identifier": "2.2",
            "registrationHints": "Scan the barcode OR register the itemNumber manually",
            "variant": "Tax-Group 19%",
            "additionalHints": "optionally provided"
          }
        ],
      }
    ]
}

这是我尝试过的代码,但我的数据库中没有任何变化:

exports.editCategoryInBook = function (body, project, salesChannelName, country) {
  mongoClient.connect(mongoUrl, async (err, client) => {
    assert.equal(null, err)
    const db = client.db(dbName)
    var categoryName = Object.keys(body)[0]
    var updateCategory = `categories.$.${categoryName}`
    var categoryValue = body[categoryName]
    console.log(`$set: { ${updateCategory}: categoryValue }`)
    db.collection(project).updateOne({
      "book": true,
      "salesChannel": salesChannelName,
      "country": country
    }, {
      $set: { [updateCategory]: categoryValue },
      $currentDate: { lastModified: true }
    })
    client.close()
  })
  return new Promise(function (resolve, reject) {
    resolve();
  });
}

这是传递给函数的主体变量:

{
    "pieceItems": [
    {
        "category": "Piece Item",
        "identifier": 1.11,
        "registrationHints": "Scan the barcode OR register the itemNumber manually; some more hints could follow",
        "variant": "Tax-Group 19%",
        "additionalHints": "some string hint to give bonus information about this item",
        "name": "Buntsteinputz 8508",
        "EAN": 4003498690070,
        "PLU": 3822584,
        "price": "51,95€"
    },
    {
        "category": "Piece Item",
        "identifier": 1.2,
        "registrationHints": "Scan the barcode OR register the itemNumber manually; some more hints could follow",
        "variant": "Tax-Group 7%",
        "additionalHints": "some string hint to give bonus information about this item",
        "name": "Buntsteinputz 8508",
        "EAN": 4003498690070,
        "PLU": 3822584,
        "price": "51,95€"
    }
  ]
}

我从 console.log 得到以下输出:

$set: { categories.$.pieceItems: categoryValue }

我得到以下错误:

MongoError: The positional operator did not find the match needed from the query.
at Function.create (C:\Users\rkrause\node_modules\mongodb\lib\core\error.js:43:12)
at toError (C:\Users\rkrause\node_modules\mongodb\lib\utils.js:149:22)
at C:\Users\rkrause\node_modules\mongodb\lib\operations\common_functions.js:376:39
at C:\Users\rkrause\node_modules\mongodb\lib\core\connection\pool.js:404:18
at processTicksAndRejections (internal/process/task_queues.js:82:9)

【问题讨论】:

  • 使用"param": true的原因是什么?
  • @Ramesh 哦谢谢!我忘了把它改成"book": true 并更新了另一个文件.. 那是错误
  • 很高兴我能帮上忙。每个人都会犯这些愚蠢的错误,只有其他人才能发现它们,因为它们是逐行进行的,而我们在检查自己的代码时不会这样做:)。
  • 您是否要添加其他字段(EAN、PLU、价格)到pieceItems 数组中的现有子文档。
  • @prasad_ 是的,如果正文有差异,我想更新整个pieceItems Array

标签: node.js mongodb


【解决方案1】:

所以现在的问题是,它不想更新其中的所有内容,除非它与过滤器部分中的某些搜索查询匹配。但我认为我们可以欺骗它这样做:

const WhatToSet = `categories.$.${categoryName}`


db.collection(project).updateOne({
  "book": true,
  "salesChannel": salesChannelName,
  "country": country,
  [`categories.${categoryName}`]: {$exists: true}
}, {
  $set: { [WhatToSet]: categoryValue },
  $currentDate: { lastModified: true }
})

希望对你有帮助

【讨论】:

  • 嗨,我想你引导我走向正确的方向。我已经更新了我的问题,您可以查看我的更改吗?
  • 也许它需要像 'categories.$.pieceItems' 但我认为那将是一个语法错误。
  • 我更新了答案。我认为我们可以欺骗 mongo 做这件事:D
  • 完美,非常感谢!我会接受你的回答。请将`categories.${categoryName}`WhatToSet设置在方括号中,因为没有它就无法工作。
  • 我不确定我是否正确编辑了它,我也不明白为什么会这样。你能详细说明一下吗?
猜你喜欢
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 2018-11-13
  • 2023-03-18
  • 2019-02-25
  • 1970-01-01
相关资源
最近更新 更多