英文:
Is there a way to update a nested object in MongoDB using Mongoose and TypeScript without replacing it completely?
问题
我想在MongoDB文档中的现有对象中附加新属性。
这是文档结构
{
_id: ObjectId('XXX'),
tenant_id: '',
ck_details: {
leadId: '',
refNum: ''
}
}
现在我想在ck_details
对象内插入appId
属性。ck_details
是一个对象,不是一个数组,所以我不想像数组一样推送它。
我已经尝试过使用$set
和updateOne()
,但它会完全更新ck_details
对象。
TenantModel.updateOne({ tenant_id: 'tenantId' }, { $set: { ck_details: { appId } } })
我还尝试了$push
,但文档建议它会将其推送为对象中的数组。
TenantModel.updateOne({ tenant_id: 'tenantId' }, { $set: { ck_details: { $push: { appId } } } })
我还尝试启用$upsert
标志,但也没有成功。
英文:
I want to append a new property to existing object in the mongodb document.
This is the document structure
{
_id: ObjectId('XXX'),
tenant_id: '',
ck_details: {
leadId: '',
refNum: ''
}
}
Now I want to insert the appId
property inside ck_details
Object. ck_details
is object not an array so I don't want to push like array.
I already tried with $set
with updateOne()
but it completely update the ck_details
Object.
TenantModel.updateOne({ tenant_id: 'tenantId' }, { $set: { ck_details: { appId } } })
I also tried with $push
but as docs suggest it will push as array in the object.
TenantModel.updateOne({ tenant_id: 'tenantId' }, { $set: { ck_details: { $push: { appId } } } })
I also tried enabling $upsert
flag but it didn't work out too.
答案1
得分: 2
从嵌套文档中设置字段文档中:
若要在嵌套文档或数组中指定
<field>
,请使用点表示法。
嵌套文档:
若要使用点表示法指定或访问嵌套文档的字段,请将嵌套文档名称与点(.)和字段名称连接,并用引号括起来。
应为:
TenantModel.updateOne(
{ tenant_id: 'tenantId' },
{ $set: { 'ck_details.appId': appId } }
)
英文:
From the Set Fields in Embedded Documents doc:
> To specify a <field>
in an embedded document or in an array, use dot notation.
> To specify or access a field of an embedded document with dot notation, concatenate the embedded document name with the dot (.) and the field name, and enclose in quotes
It should be :
TenantModel.updateOne(
{ tenant_id: 'tenantId' },
{ $set: { 'ck_details.appId': appId } }
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论