使用 mongoose 和 NestJS 自动增量字段

Pur*_*mar 2 mongoose typescript nestjs

有人可以指导我如何在将 mongoose 与 NestJS 框架一起使用时自动递增集合内的任何字段。

例如:假设我有这个用户模式

@Schema()
export class User extends Document {
    @Prop()
    userId: number;  // I want to increment this field on each new user
    
    @Prop()
    name: string;

    @Prop({
        type: String,
        required: true,
        unique: true,
    })
    email: string;

    @Prop()
    isEmailVerified: boolean;

    @Prop({
        type: String,
        required: true,
        unique: true,
    })
    mobile: string;

    @Prop()
    isMobileVerified: boolean;

    @Prop({
        type: String,
        required: true,
    })
    password: string;

}

export const UserSchema = SchemaFactory.createForClass(User);
Run Code Online (Sandbox Code Playgroud)

我想增加每个新用户的 userId 。谢谢

小智 7

Schema 装饰器有一个 SchemaOptions 类型的选项参数:

@Schema({ timestamps: true })

如果你想重命名时间戳:

@Schema({ timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }})