Purushotam Kumar
Purushotam Kumar

Reputation: 1092

Autoincrement of field with mongoose and nestJS

Can someone guide me how can I auto increment any field inside the collection while using mongoose with nestJS framework.

e.g: Suppose I have this user schema

@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);

I want to increment userId on each new user. Thanks

Upvotes: 2

Views: 3963

Answers (3)

Ashin Thankachan
Ashin Thankachan

Reputation: 158

Try This, if are also using other schema in mongoosemodule.forfeature(....) ,add this also


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

Upvotes: 1

godlerner
godlerner

Reputation: 129

The Schema decorator has an options parameter of type SchemaOptions:

@Schema({ timestamps: true })

If you want to rename the timestamps:

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

Upvotes: 7

Hani Ghazi
Hani Ghazi

Reputation: 118

EDIT

since you asked for a code example... I'm using typescript with this library ts-mongoose-pagination to manage the pagination stuff over the card schema, btw I'm using Nestjs

card.sceham.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};

app.module.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 {}

card.service.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)
  }
}

Hope this resolve your issue

Upvotes: 2

Related Questions