【发布时间】: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')
【问题讨论】:
-
country字段是一个嵌入文档。要使用嵌入的文档字段,请使用 dot notation。
标签: javascript reactjs mongodb mongoose