I have a NestJS project in which I have the following mongoose schema for a “tag”:
@Schema()
export class Tag {
@Prop({
type: String,
trim: true,
lowercase: true,
required: true })
name: string;
@Prop({type: Object})
locales: object;
@Prop({ type: SchemaTypes.ObjectId })
parent: Types.ObjectId;
@Prop({ type: String, default: 'none'})
owner: string;
@Prop({ type: Date, default: now })
inserted: Date;
@Prop({ type: String, required: true})
insertedby: string;
@Prop({ type: Boolean, default: false })
isMarkedForDeletion: boolean;
}
via the API, the user can modify the name and locales for a tag.
For this, I tried first a code similar to this:
async update(id: string, updateTagDto: UpdateTagDto, reqtenant: string): Promise<TagEntity> {
let tag = await this.tagModel.findById(id);
if('name' in updateTagDto) {
tag.set(name, updateTagDto.name);
}
if('locales' in updateTagDto) {
let currentLocales = tag.get('locales');
for (const [key, value] of Object.entries(updateTagDto.locales)) {
currentLocales[key] = value;
}
tag.set('locales', currentLocales);
// tag.set({locales: currentLocales}); // Tried this ways as well
}
}
const modTag = await tag.save();
return {
tagId: tag.get('_id'),
name: tag.get('name'),
parent: tag.get('parent')?.toString(),
owner: tag.get('owner'),
inserted: tag.get('inserted'),
insertedby: tag.get('insertedby'),
locales: tag.get('locales')
}
}
This works correctly to update “name”, but it does not work for “locales”. I do actually see in the debugger that the doc inside modTag and inside tag both have the new locales after executing save(), but locales are not updated in the database.
It works, however, if I do it this way:
let currentLocales = null;
if('locales' in updateTagDto) {
currentLocales = tag.get('locales');
for (const [key, value] of Object.entries(locales)) {
currentLocales[key] = value;
}
}
if(currentLocales) {
tag = await this.tagModel.findByIdAndUpdate(id, { locales: currentLocales });
}
According to mongoose documentation, the save() option is preferred because save() performs validation. But why is it not working?
Obviously, I can just use findByIdAndUpdate to update the whole document and not only “locales”, but I would like to understand what I might be doing wrong with save() or if it might be a bug in the “mongoose” or “@nestjs/mongoose” that are used under the hood, in which case I would try to report to the relevant repository.