Mongoose 在 updateMany 中设置对象 ID

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

Mongoose setting Object IDs in updateMany

问题

I need to add IDs to many objects inside an array. Here's your code:

db.collection('collectionName').updateMany(
  { animals: { $ne: [] } },
  {
    $set: {
      'animals.$[].cats.$[]._id': mongoose.Types.ObjectId(),
      'animals.$[].dogs.$[]._id': mongoose.Types.ObjectId()
    }
  }
);

It's working, but the IDs are the same. To achieve unique IDs, you can generate a new unique ID for each object individually. Here's an updated code snippet:

db.collection('collectionName').updateMany(
  { animals: { $ne: [] } },
  {
    $set: {
      'animals.$[].cats.$[]._id': { $each: [mongoose.Types.ObjectId()] },
      'animals.$[].dogs.$[]._id': { $each: [mongoose.Types.ObjectId()] }
    }
  }
);

This code will generate a unique ID for each cat and dog object inside the arrays.

英文:

I need to add IDs to many object inside of array inside. Assume that my schema looks like this:

{
   _id: something,
   property:value,
   animals: [
     {
       dogs: [
         { name: 'Dog1' },
         { name: 'Dog2' }
       ],
       cats: [
         { name: 'Cat1' },
         { name: 'Cat2' }
       ]
     }
   ]
}

I want to achieve something like this:

{
   _id: something,
   property:value,
   animals: [
     {
       dogs: [
         { name: 'Dog1', _id: uniqueID },
         { name: 'Dog2', _id: uniqueID }
       ],
       cats: [
         { name: 'Cat1', _id: uniqueID },
         { name: 'Cat2', _id: uniqueID }
       ]
     }
   ]
}

My code

db.collection('collectionName').updateMany(
  { animals: { $ne: [] } },
       {
          $set: {
            'animals.$[].cats.$[]._id': mongoose.Types.ObjectId(),
            'animals.$[].dogs.$[]._id': mongoose.Types.ObjectId()
          }
       }
 );

It works but IDs are exactly the same. How to achieve unique IDs?

答案1

得分: 1

这是因为 mongoose.Types.ObjectId() 是一个客户端函数。它在构建查询时执行,只有函数调用返回的值会包含在提交给服务器的请求中。

英文:

That happens because mongoose.Types.ObjectId() is a client-side function. It is executed while building the query, and only the value returned by the function call is included in the request submitted to the server.

huangapple
  • 本文由 发表于 2023年4月20日 01:09:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057159.html
匿名

发表评论

匿名网友

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

确定