【问题标题】:How to update only if my object has a certain field仅当我的对象具有特定字段时如何更新
【发布时间】:2021-12-12 08:57:14
【问题描述】:

我有一个这样的 mongo db 文档

id: ObjectId(asdlkjjas_48@$#),
_user: 4593oawifjaslef,
country: { US: false, CA: false, MX: false, FR: false }
name: "kevin"
age: 28

我收到来自前端的 post 请求,其中包含 objectId(需要查询此文档)以及国家/地区代码

所以我的用户将他们的 ID 和 countryCode 发送到后端,我需要更新与该 ID 匹配的文档,并且只更新嵌套在 country 中的 countryCode。

我尝试这样的事情

incomingNumber = await Collection.findById(numberId) // get our document by id
const code = 'US' // get our country code
collection.updateOne({_id: incomingNumber}, {$set: { country[code]: true }}) //trying to update only the field in country(object) that matches our supplied country code(ex. 'US')

【问题讨论】:

标签: javascript reactjs mongodb mongoose


【解决方案1】:

有人发布了几秒钟的答案然后删除,重新发布你的答案,我会给你信用。

答案是

Collection.updateOne({_id: incomingNumber}, {$set: { country: { [code]: true}}})

我基本上需要一个额外的花括号。在这种情况下这对我有用,但是 Country 对象现在看起来像这样

{ US: true },

我宁愿有

 { US: true, FR: false, MX: false, CA: false }

【讨论】:

  • 嘿,看看我写的答案。
【解决方案2】:

为了保留country 对象并保留未更新的键,您可以使用模板文字(因为它是猫鼬)或使用方括号,

Collection.updateOne({_id: objectId}, {$set: { ["country."+code]: true}})

Collection.updateOne({_id: objectId}, {$set: { `country.${code}`: true}})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多