Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Plugins nestjs

How can I implement the mongoose plugin using nestjs?

import * as mongoose from 'mongoose';
import uniqueValidator from 'mongoose-unique-validator';
import mongoosePaginate from 'mongoose-paginate';
import 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 });

Error: First param to schema.plugin() must be a function, got "undefined"

like image 983
Walter Armando Cruz Avatar asked Mar 20 '18 14:03

Walter Armando Cruz


People also ask

What are plugins in mongoose?

Plugins are a tool for reusing logic in multiple schemas. Suppose you have several models in your database and want to add a loadedAt property to each one. Just create a plugin once and apply it to each Schema : // loadedAt.

Is NestJS better than express?

Since ExpressJS doesn't follow MVC, there's no proper structure which makes the application inefficient and less optimized. NestJS becomes a better choice for developers as it is clearly based on an architecture with components like modules, controllers, and providers.

Should we use mongoose?

Pros/Cons of using Mongoose: Biggest Pro is that it has the data validation built into it(requirements of what data you will allow to be added or to update your database). It will take some work to build that yourself. (but not THAT hard) It will abstract away most of the mongoDB code from the rest of the application.


3 Answers

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 {}
like image 100
tamir Avatar answered Sep 21 '22 03:09

tamir


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

  1. 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 schema
MessageSchema.plugin(mongoosePaginate);
  1. Now in the Message interface document
export interface Message extends Document {
// Your schema fields here
}

  1. 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);
    }
}
like image 43
Sandeep K Nair Avatar answered Sep 24 '22 03:09

Sandeep K Nair


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'
like image 22
Ramiro Martinez Avatar answered Sep 23 '22 03:09

Ramiro Martinez