我是打字稿和NestJS框架的新手。目前我想在我的应用程序中为所有模型实现分页机制。在当前的api项目中,我使用的是带有猫鼬的NestJS。
我的用户原理如下
export const UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
phone: String,
password: {
type: String
}
});
UserSchema.plugin(mongoosePaginate);
UserSchema.plugin(passportLocalMongoose, {
usernameField: 'email',
});
我的用户界面如下:
export interface IUser extends PassportLocalDocument {
readonly firstName: string;
readonly lastName: string;
readonly email: string;
readonly phone: string;
readonly password: string;
}
我的userService如下:
@Injectable()
export class UsersService implements IUsersService {
constructor(@InjectModel('User') private readonly userModel: PassportLocalModel<IUser>) {
}
async findAll(): Promise<IUser[]> {
return await this.userModel.find().exec();
}
我想通过我的用户界面添加mongoose-paginate功能,所以我可以通过qazxsw poi在服务中访问它。
我提到我安装了:this.userModel.paginate
和"@types/mongoose-paginate": "^5.0.6"
,我可以从"mongoose-paginate": "^5.0.3"
导入PaginateModel
。
我想mongoose
界面应该是这样的:
IUser
但我不确定,也不知道在注入服务时如何实例化它。
等你的回复家伙,谢谢! :d
我在另一个问题上处理了这个情况。我创建了2个接口,1个用于注册/认证,另一个用于数据操作。
导入PaginateModel后,您必须使用export interface IUser<T extends PassportLocalDocument > extends PaginateModel<T> {}
扩展您的界面。
Document
之后,当您将其注入您的服务:
export interface IUser extends Document
最后,在您的服务接口和服务实现中,更改返回类型,如下所示:
@InjectModel('User') private readonly userModel: PaginateModel<IUser>
对于那些使用带有nestjs的async findAll(yourParams: YourParamsDto): Promise<PaginateResult<IUser>>
插件的人来说,这是一个片段。您也可以安装mongoose-paginate以获得打字支持
@types/mongoose-paginate
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
}