簡體   English   中英

Typescript 與 Mongoose 分頁,靜態方法

[英]Typescript with Mongoose Paginate, statics methods

來自尼泊爾的問候。

我想知道當您需要 Paginate Model 和 mongoose Model 中的靜態方法時,你們是如何做到的。

要在 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;

如何同時使用靜態方法和分頁

如果我聲明這樣的類型 const User = mongoose`.model<IUserDocument, IUserModel>("User", UserSchema);

然后我不能使用AdminModel.paginate();

如果我聲明這樣的類型 const User = mongoose`.model<IUserDocument, PaginateModel>("User", UserSchema);

然后我不能使用AdminModel.findByUsername();

由於 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