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"
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.
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.
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.
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 {}
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
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);
export interface Message extends Document {
// Your schema fields here
}
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With