简体   繁体   English

Typescript 与 Mongoose 分页,静态方法

[英]Typescript with Mongoose Paginate, statics methods

Greetings from Nepal.来自尼泊尔的问候。

I am wondering how you guys do it when you need Paginate Model and statics method in mongoose Model.我想知道当您需要 Paginate Model 和 mongoose Model 中的静态方法时,你们是如何做到的。

To use statics and methods function in mongoose model, I use this code:要在 mongoose model 中使用静态和方法 function,我使用以下代码:

import mongoose, { Schema, Document, Model } from "mongoose";
import bcrypt from "bcrypt";
import mongoosePaginate from 'mongoose-paginate-v2';

interface IUser {
    username: string;
    hashedPassword: string;
}

interface IUserDocument extends IUser, Document {
    setPassword: (password: string) => Promise<void>;
    checkPassword: (password: string) => Promise<boolean>;
}

interface IUserModel extends Model<IUserDocument> {
    findByUsername: (username: string) => Promise<IUserDocument>;
}

const UserSchema: Schema<IUserDocument> = new Schema({
    username: { type: String, required: true },
    hashedPassword: { type: String, required: true },
});

UserSchema.methods.setPassword = async function (password: string) {
    const hash = await bcrypt.hash(password, 10);
    this.hashedPassword = hash;
};

UserSchema.methods.checkPassword = async function (password: string) {
    const result = await bcrypt.compare(password, this.hashedPassword);
    return result;
};

UserSchema.statics.findByUsername = function (username: string) {
    return this.findOne({ username });
};
UserSchema.plugin(mongoosePaginate);
const User = mongoose.model<IUserDocument, PaginateModel<IUserDocument>>("User", UserSchema);
export default User;

How to use statics methods and Paginate at the same time如何同时使用静态方法和分页

if I declare type like this const User = mongoose`.model<IUserDocument, IUserModel>("User", UserSchema);如果我声明这样的类型 const User = mongoose`.model<IUserDocument, IUserModel>("User", UserSchema);

Then I cannot use AdminModel.paginate();然后我不能使用AdminModel.paginate();

and if I declare type like this const User = mongoose`.model<IUserDocument, PaginateModel>("User", UserSchema);如果我声明这样的类型 const User = mongoose`.model<IUserDocument, PaginateModel>("User", UserSchema);

Then I cannot use AdminModel.findByUsername();然后我不能使用AdminModel.findByUsername();

Since both PaginateModel and UserModel extends the mongoose Model so the intersection of this two types might work:由于 PaginateModel 和UserModelextendsPaginateModel Model所以这两种类型的intersection可能会起作用:

import {PaginateModel} from "mongoose"

// ...

const User = model<UserDocument, PaginateModel<UserDocument> & UserModel>("User", UserSchema);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM