Home > Enterprise >  Use nestjs to add unique ObjectID to each document that doesn't have one
Use nestjs to add unique ObjectID to each document that doesn't have one

Time:07-13

Just looking for a bit of guidance. I am connected to my local mongoDB instance and I am trying to build a query that will add a unique objectID to every object in an array that doesn't have an _id already. I am trying to do this in nestjs so I can utilize javascript and get a unique ObjectID. Here is what I have so far.

    const temp = await this.vehiclesRepository.updateMany(
      {
        $stipulations: [],
      },
      {
        $set: {
          $stipulations: {
            $function: {
              body: "function (ar) {return ar.map(x => { if(x.hasOwnProperty('_id')) return x; else {x['_id']=new ObjectId(); return x;}})}",
              args: ['$stipulations'],
              lang: 'js',
            },
          },
        },
      },
    );
  public async updateMany(filter: FilterQuery<T>, doc: UpdateQuery<T>) {
    this.model.updateMany(filter, doc, { upsert: true, multi: true });
  }

Can anyone tell me where I am going wrong with this? Based on my research this seems like the proper method to accomplish this task.

CodePudding user response:

The $function operator is an aggregation operator. You should use it within an aggregation pipeline. There is also a $set operator specifically meant for aggregations.

You should combine the $function and $set (aggregation) operators within an aggregation pipeline.

CodePudding user response:

I was able to answer my question in the MongoDB shell, with no javascript like so

db.vehicles.find().forEach(function(doc){
    if(doc.stipulations != null) {
        if(doc.stipulations.length > 0) {
            doc.stipulations.forEach(function(stip) {
                if(stip._id == null) {
                    stip._id = new ObjectId();
                }
            });
        }
    }
    db.vehicles.updateOne({_id: doc._id}, {$set: doc});
});

For optimization it is possible to filter purely in find(), but for this one time query I am not posting that.

  • Related