Typescript mongoose和nestJS字段的自动递增

Typescript mongoose和nestJS字段的自动递增,typescript,mongoose,nestjs,Typescript,Mongoose,Nestjs,有人能告诉我如何在使用mongoose和nestJS框架时自动增加集合中的任何字段吗 e、 g:假设我有这个用户模式 @Schema() export class User extends Document { @Prop() userId: number; // I want to increment this field on each new user @Prop() name: string; @Prop({ type

有人能告诉我如何在使用mongoose和nestJS框架时自动增加集合中的任何字段吗

e、 g:假设我有这个用户模式

@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);
我想增加每个新用户的userId。谢谢

编辑 既然您要求提供一个代码示例。。。我在这个库ts mongoose分页中使用typescript来管理卡片模式上的分页内容,顺便说一句,我使用的是Nestjs

卡德·斯切姆·ts app.module.ts card.service.ts 希望这能解决您的问题

EDIT 既然您要求提供一个代码示例。。。我在这个库ts mongoose分页中使用typescript来管理卡片模式上的分页内容,顺便说一句,我使用的是Nestjs

卡德·斯切姆·ts app.module.ts card.service.ts
希望这能解决您的问题

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

@架构{时间戳:true}

如果要重命名时间戳,请执行以下操作:


@架构{timestamps:{createdAt:'created_at',updatedAt:'updated_at'}

架构装饰器具有SchemaOptions类型的选项参数:

@架构{时间戳:true}

如果要重命名时间戳,请执行以下操作:


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

我想这是一个重复的问题,请检查nestJs的体系结构是否与node略有不同。我已经尝试过这个东西,但我无法弄清楚,我怎么能在nestJS中应用相同的东西。我猜这是重复的问题,请检查nestJS的架构与node的架构有什么不同。我已经尝试过这个东西,但我不知道如何在nestJS中应用同样的东西。是的,我知道这个插件,我只是想了解这些插件在nestJS中的实现。你能给我一些代码示例吗?@SiddharthChandra我已经编辑了完整的Nestjs示例的答案,看一看,我知道如何使用模式应用插件。如果插件需要db连接对象呢?自动增量插件需要DB连接才能工作。是的,我知道该插件,我只是想了解这些插件在nest js中的实现。你能给我一些代码示例吗?@SiddharthChandra我已经编辑了完整的Nestjs示例的答案,看一看,我知道如何使用模式应用插件。如果插件需要db连接对象呢?自动增量插件需要DB连接才能工作。
import {  Schema, Types } from 'mongoose';
import { CardTypesEnum } from '../utils/constants';
import { mongoosePagination } from "ts-mongoose-pagination";

const CardSchema = new Schema({
  isOriginal: Boolean,
  parentCard: {type: Types.ObjectId, ref: 'Card'},
  patientId: String,
  coverImage: String,
  title: String,
  content: String,
  createdBy: String,
  tags: [String],
  type: {
    type: String,
    default: CardTypesEnum.NORMAL,
    enum: Object.values(CardTypesEnum),
  },
}, {
  timestamps: true,
});


CardSchema.plugin(mongoosePagination);

export {CardSchema};
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { CardService } from './card.service';
import { ScheduleModule } from '@nestjs/schedule';
import { MongooseModule } from '@nestjs/mongoose';
import { CardSchema } from './schemas/card.shcema';
import * as config from 'config';

const {DB_HOST} = config.get('DB');


@Module({
  imports: [
    MongooseModule.forRoot(process.env.DB || DB_HOST, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }),
    MongooseModule.forFeature([
      {
        name: 'Card',
        schema: CardSchema,
      }
    ]),
    ScheduleModule.forRoot()],
  controllers: [AppController],
  providers: [CardService],
})
export class AppModule {}
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { IPaginateResult, Model, PaginateModel } from 'mongoose';
import { CardsListFilterDto, CardDto } from './utils/dto/Cards.dto';
import { QueryOptionsDto } from './utils/dto/db.dto';

@Injectable()
export class CardService {
  private readonly logger = new Logger(CardService.name);
  constructor(
    // cardModel type is not Model but PaginateModel (so you can use the paginate method)
    @InjectModel('Card') private readonly cardModel: PaginateModel<any>,
  ) {}
  async getCardLists(cardsListFilterDto: CardsListFilterDto): Promise<IPaginateResult<any>> {
    const optionsDto: QueryOptionsDto = {
       page: parseInt(cardsListFilterDto.page),
       perPage: parseInt(cardsListFilterDto.perPage),
       sort: {'_id': -1}
    };
    const where = {
      createdBy: cardsListFilterDto.createdBy,
      isOriginal: true,
    };
    // you can have paginate method by adding the plugin to schema
    return await this.cardModel.paginate(where, optionsDto)
  }
}