使用Mongoose和nestJS自动增加字段

lmyy7pcs  于 2023-01-21  发布在  Go
关注(0)|答案(3)|浏览(129)

有人能指导我如何在使用mondoose和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);

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

ovfsdjhp

ovfsdjhp1#

Schema装饰器有一个SchemaOptions类型的options参数:
@Schema({ timestamps: true })
如果要重命名时间戳:
@Schema({ timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }})

taor4pac

taor4pac2#

编辑

既然您要求提供代码示例......我正在使用typescript和ts-mongoose-pagination库来管理卡片架构上的分页内容,顺便说一句,我使用的是Nestjs

卡片扫描表ts

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};

应用程序模块.ts

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 {}

卡服务ts

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)
  }
}

希望这能解决您的问题

ljo96ir5

ljo96ir53#

试试这个,如果你也在mongoosemodule.forfeature(....)中使用其他模式,也添加这个

import {getConnectionToken, MongooseModule} from '@nestjs/mongoose';
    import * as AutoIncrementFactory from 'mongoose-sequence';
    
    @Module({
      imports: [
        MongooseModule.forFeatureAsync([
          {
            name: User.name,
            useFactory: async (connection: Connection) => {
              const schema = UserSchema;
              const AutoIncrement = AutoIncrementFactory(connection);
              schema.plugin(AutoIncrement, {id:"user_seq",inc_field: 'userId'});
              return schema;
            },
            inject: [getConnectionToken()],
          },
        ]),
      ],
    })

export class AppModule {}

相关问题