【问题标题】:MongoDB nested search query parametersMongoDB 嵌套搜索查询参数
【发布时间】:2021-12-19 02:40:19
【问题描述】:

是否有机会通过"ID" "lang" 字段触发记录,使用findOneAndUpdatefindByIdAndUpdate 查询MongoDB 记录?这是数据库对象示例:

{
        "id": "61842e6fb19afbc0922f5505",
        "locales": [
          {
            "lang": "ru",
            "title": "Тестовый десерт",
            "description": "тестовый"
          },
          {
            "lang": "lv",
            "title": "Testu deserts",
            "description": "Testu descriptions"
          },
          {
            "lang": "en",
            "title": "Test dessert",
            "description": "Test description"
          }
        ]
}

这就是我尝试触发的方式,但它不起作用:

const filter = {
  _id: id,
  locales: {
    lang: lang
  }
}

const product = await Product.findOneAndUpdate(filter, {
  lang: {
    title,
    description,
    price
  }
}, { new: true });

【问题讨论】:

    标签: javascript mongodb mongoose graphql


    【解决方案1】:

    您可以像这样使用$set 运算符:

    const product = await Product.findOneAndUpdate({
      _id: "61842e6fb19afbc0922f5505",
      "locales.lang": "ru"
    },
    {
      "$set": {
        "locales.$": {
          lang: "ru",
          title: "title",
          description: "desription",
          price: 23
        }
      }
    })
    

    工作场所:https://mongoplayground.net/p/oBNS6wtK50g

    【讨论】:

    • 非常感谢!这有效
    猜你喜欢
    • 2015-06-29
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 2021-09-01
    • 2015-09-24
    • 1970-01-01
    • 2013-06-22
    相关资源
    最近更新 更多