Typegoose v10 timestamps: true model option not creating `createdAt` and `updatedAt` properties when creating an object

262 Views Asked by At

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:

  1. Using @modelOptions decorator

    @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;
    
  2. Extexteding from TimeStamps class

     export class User extends TimeStamps {
     @prop({ type: () => String, required: true })
         name: string;
     }
     const UserModel = getModelForClass(User);
    
     export default UserModel;
    
  3. 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
0

There are 0 best solutions below