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.
2
Answers
I was able to answer my question in the MongoDB shell, with no javascript like so
For optimization it is possible to filter purely in find(), but for this one time query I am not posting that.
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.