Mongoose Plugins nestjs
This is a snippet for those who are using mongoose-paginate plugin with nestjs. You can also install @types/mongoose-paginate for getting the typings support
- Code for adding the paginate plugin to the schema:
import { Schema } from 'mongoose';import * as mongoosePaginate from 'mongoose-paginate';export const MessageSchema = new Schema({// Your schema definitions here});// Register plugin with the schemaMessageSchema.plugin(mongoosePaginate);
- Now in the Message interface document
export interface Message extends Document {// Your schema fields here}
- Now you can easily get the paginate method inside the service class like so
import { Injectable } from '@nestjs/common';import { InjectModel } from '@nestjs/mongoose';import { PaginateModel } from 'mongoose';import { Message } from './interfaces/message.interface';@Injectable()export class MessagesService { constructor( // The 'PaginateModel' will provide the necessary pagination methods @InjectModel('Message') private readonly messageModel: PaginateModel<Message>, ) {} /** * Find all messages in a channel * * @param {string} channelId * @param {number} [page=1] * @param {number} [limit=10] * @returns * @memberof MessagesService */ async findAllByChannelIdPaginated(channelId: string, page: number = 1, limit: number = 10) { const options = { populate: [ // Your foreign key fields to populate ], page: Number(page), limit: Number(limit), }; // Get the data from database return await this.messageModel.paginate({ channel: channelId }, options); }}
Try this:
import * as mongoose from 'mongoose';import * as uniqueValidator from 'mongoose-unique-validator';import * as mongoosePaginate from 'mongoose-paginate';import * as mongoose_delete from 'mongoose-delete';const UsuarioSchema = new mongoose.Schema({ username: { type: String, unique: true, required: [true, 'El nombre de usuario es requerido'] }, password: { type: String, required: [true, 'La clave es requerida'], select: false }});UsuarioSchema.plugin(uniqueValidator, { message: '{PATH} debe ser Ășnico' });UsuarioSchema.plugin(mongoosePaginate);UsuarioSchema.plugin(mongoose_delete, { deletedAt : true, deletedBy : true, overrideMethods: true });export default UsuarioSchema;
Then you can use it like this:
import UsuarioSchema from './UsuarioSchema'
NestJS Documentation has better way to add plugins to either individual schema.
@Module({ imports: [ MongooseModule.forFeatureAsync([ { name: Cat.name, useFactory: () => { const schema = CatsSchema; schema.plugin(require('mongoose-autopopulate')); return schema; }, }, ]), ],})export class AppModule {}
Or if at global level.
import { Module } from '@nestjs/common';import { MongooseModule } from '@nestjs/mongoose';@Module({ imports: [ MongooseModule.forRoot('mongodb://localhost/test', { connectionFactory: (connection) => { connection.plugin(require('mongoose-autopopulate')); return connection; } }), ],})export class AppModule {}