Is there a way to update a nested object in MongoDB using Mongoose and TypeScript without replacing it completely?

huangapple go评论64阅读模式
英文:

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是一个对象,不是一个数组,所以我不想像数组一样推送它。

我已经尝试过使用$setupdateOne(),但它会完全更新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 &lt;field&gt; in an embedded document or in an array, use dot notation.

Embedded Documents

> 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: &#39;tenantId&#39; }, 
  { $set: { &#39;ck_details.appId&#39;: appId } }
)

huangapple
  • 本文由 发表于 2023年5月26日 13:19:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定