Currently, my code is set up to add new flagDtos
using $addToSet
without consideration for the uniqueness of item.name
. However, I want to change this behavior so that:
- If
item.name
is unique, add the newflagDtos
object. - Otherwise, update the existing
flagDto
if it matches aitem.name
.
I am looking for a way to conditionally use $addToSet. Any suggestions on how to achieve this?
async addFlagsToFeature(_id: number, flagDtos: FlagDto[]): Promise<FeatureResponse> {
const filter: FilterQuery<FeatureDocument> = { _id };
let success;
var flagIds = [];
return this.featureModel
.findOneAndUpdate({ filter, $addToSet: { flags: flagDtos } })
.then((doc) => {
const featureDto = new FeatureDto();
featureDto.mapFromSchema(doc);
featureDto.flags.forEach((item) => {
flagIds.push(new FlagDto({ featureFlagId: item.featureFlagId }));
success = new SuccessFeatureResponseDto(featureDto.id, flagIds);
});
return new FeatureResponse(success, null);
})
}
Below is the structure of my FlagDto
class:
export class FlagDto {
featureFlagId?: string;
name: string;
}