Search code examples
arraysmongodbmongoosemongodb-querymongoose-schema

How to use mongoose auto increment inside a array in mongoDB


I need to use integer numbers for my array object ID. now in mongoDB the default _id for array objects are ObjectId('62e10eb9150cd328edd6f6y3') and i need to change that to integer numbers. Can I know is that possible or not. If that possible please mention how to do that.


Solution

  • now in mongoDB the default _id for array objects are ObjectId('62e10eb9150cd328edd6f6y3')

    This is not true, this is true for mongoose as it generates an ObjectId for each object by default - but this is not a MongoDB feature.

    mongoose does not offer any alternatives as a feature, in your case using index of array as _id, but you can work around it by executing a slightly less efficient update using the aggregation pipeline syntax, like so:

    const newArrayItem = { ... new array items };
    
    db.collection.updateOne(
    {},
    [
      {
        "$set": {
          "items": {
            $concatArrays: [
              {
                $ifNull: [
                  "$items",
                  []
                ]
              },
              [
                {
                  $mergeObjects: [
                    newArrayItem,
                    {
                      _id: {
                        $size: {
                          $ifNull: [
                            "$items",
                            []
                          ]
                        }
                      }
                    }
                  ]
                }
              ]
            ]
          }
        }
      }
    ])
    

    Mongo Playground