Node.js – 在Mongodb对象的数组中添加新字段

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

Node.js- Add new field in array of Mongodb object

问题

我有一个用户集合,其中包含多个车牌的数组:

users: [
{
    _id: '61234XXX',
    plates: [
        {
            _id: '123',
            'color': 'orange'
        },
        {
            _id: '124',
            'color': 'blue'
        }
    ]
},
{
    _id: '63456XXX',
    plates: [
        {
            _id: '321',
            'color': 'orange'
        },
        {
            _id: '432',
            'color': 'green'
        }
    ]
}
]

我试图找出一种方法,为每个用户的所有当前车牌对象添加一个新字段:

我已经做到了这一点:

await User.findOneAndUpdate(
    { _id: '63456XXX' },
    {
        $set : {
            ['plates.0.plateStyle']: "testValue"
        }
    }
)

尽管这样做是有效的,但并不适合此目的。我是否有更好的方法可以遍历这些对象?

英文:

I have a collection of users that has an array of multiple plates :

users : [
{
_id: '61234XXX'
plates: [
 {
   _id: '123'
   'color': 'orange'
 },
 {
   _id: '124'
   'color': 'blue'
 }
]
},
{
_id: '63456XXX'
plates: [
 {
   _id: '321'
   'color': 'orange'
 },
 {
   _id: '432'
   'color': 'green'
 }
]
}
]

I'm trying to figure out a way to add a new field to the all current plate objects for every user:

I've got to this:

  await User.findOneAndUpdate(
      { _id: '63456XXX' },
      {
        $set : {
          [`plates.0.plateStyle`]: "testValue"
        }
      }
  )

Tho this works it's not fit for purpose. Is there a better way I can iterate over this?

答案1

得分: 1

以下是翻译好的内容:

你可以尝试这个查询:

在这里,你使用 array filters 来告诉 MongoDB:“当你找到一个具有 _id: "61234XXX"存在 plates 的对象时,在那里获取匹配 plates 不为空(以获取所有内容)的文档 (elem) 并添加 plateStyle”。

await User.updateMany({
  _id: "61234XXX",
  plates: {
    $exists: true
  }
},
{
  $set: {
    "plates.$[elem].plateStyle": "testValue"
  }
},
{
  arrayFilters: [
    {
      elem: { $ne: [ "$plates", [] ] }
    }
  ]
})

示例 在这里

另外,如果你是通过 _id 进行查找,那么不需要使用 updateMany,因为 _id 是唯一的,结果只会是 1 个或 0 个。

英文:

You can try this query:

Here you are using array filters to tell mongo: "Where you find an object with _id: "61234XXX" and exists the plates then, there, get the document (elem) which match that plates is not empty (to get all) and add plateStyle".

await User.updateMany({
  _id: "61234XXX",
  plates: {
    $exists: true
  }
},
{
  $set: {
    "plates.$[elem].plateStyle": "testValue"
  }
},
{
  arrayFilters: [
    {
      elem: { $ne: [ "$plates", [] ] }
    }
  ]
})

Example here

Also if you are finding by _id you won't need updateMany since _id is unique and only will be 1 or 0 results.

huangapple
  • 本文由 发表于 2023年1月10日 04:49:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75062773.html
匿名

发表评论

匿名网友

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

确定