[英]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 和UserModel
都extends
了PaginateModel
Model
所以這兩種類型的intersection
可能會起作用:
import {PaginateModel} from "mongoose"
// ...
const User = model<UserDocument, PaginateModel<UserDocument> & UserModel>("User", UserSchema);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.