猫鼬插件 nestjs [英] Mongoose Plugins nestjs
本文介绍了猫鼬插件 nestjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 nestjs 实现 mongoose 插件?
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 });
错误:schema.plugin()
的第一个参数必须是一个函数,得到未定义"
Error: First param to schema.plugin()
must be a function, got "undefined"
推荐答案
这是给那些使用 mongoose-paginate 插件与 nestjs.您还可以安装 @types/mongoose-paginate 以获得类型支持
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);
- 现在在 Message 接口文档中
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);
}
}
这篇关于猫鼬插件 nestjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文