Reputation: 1092
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
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
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
Reputation: 118
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
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)
}
}
Hope this resolve your issue
Upvotes: 2