I want to add an element to the array of all collections in the city collection, but Mongo creates the ID as duplicate.
this is my code
await this.cityRepository.updateMany(
{},
{
$push: {
tags: {
title: tagValue.title,
description: tagValue.description,
applyToAllCity: tagValue.cityId ? false : true,
},
},
},
);
City Schema
export class BaseCity extends Document {
@Prop({
type: String,
required: true,
})
_id: string;
@Prop({ type: String, unique: true })
code: string;
@Prop({ type: String, ref: Province.name })
province: string | Province;
@Prop({ type: String })
faName: string;
}
@Schema({ timestamps: true })
@Schema({ collection: 'city', virtuals: true, _id: false, timestamps: true })
export class City extends BaseCity {
@Prop({ type: String })
imageName: string;
@Prop({ index: true, type: String })
enName: string;
@Prop({ type: Number })
displayOrder: number;
@Prop({ type: Boolean })
isFeatured: boolean;
@Prop({ type: Boolean })
isEnabled: boolean;
@Prop({ type: Coordinate })
coordinate: Coordinate;
@Prop([{ type: Region, ref: Region.name, default: [] }])
region: Region[];
@Prop([{ type: SubMenu }])
subMenu: SubMenu[];
@Prop([{ type: CityTags }])
tags: CityTags[];
}
const CitySchema = SchemaFactory.createForClass(City);
CitySchema.index({ faName: 'text' });
export { CitySchema };
DB
As you can see, ID 63ec8f47efbd82c8face341a is duplicated in all documents.
Is there a solution to solve this problem?
To avoid duplicate IDs, you could use the
$addToSet
instead of$push
. The$addToSet
adds an element to an array only if it does not already exist in the set.Check this:
Update:
To keep unique ids