I'm trying to create a model for User and I want to add createdAt and updatedAt properties automatically whenever an object is created or updated(this need to happen even if the object is created using MongoDB compass). I have tried:
Using
@modelOptionsdecorator@modelOptions({ schemaOptions: { timestamps: true, collection: COLLECTIONS.User, }, options: { allowMixed: Severity.ALLOW, }, }) export class User { @prop({ type: () => String, required: true }) name: string; } const UserModel = getModelForClass(User); export default UserModel;Extexteding from
TimeStampsclassexport class User extends TimeStamps { @prop({ type: () => String, required: true }) name: string; } const UserModel = getModelForClass(User); export default UserModel;and finally by,
export class User { @prop({ type: () => String, required: true }) name: string; } const UserModel = getModelForClass(User, schemaOptions: { timestamps: true, collection: COLLECTIONS.User, }, options: { allowMixed: Severity.ALLOW, },); export default UserModel;
None of these methods worked. It creates the document in the user collection but the createdAt, updatedAt fields are not in the doc.
I'm using
- node v18.
- mongoose v6.11.5
- typegoose v10.4.0