[英]Typescript error when I try to use mongoose methods
I have a User interface:我有一个用户界面:
import {Document} from "mongoose";
export interface IUser extends Document{
email: string;
password: string;
strategy: string;
userId: string;
isValidPassword(password: string): boolean;
}
And a schema:和一个模式:
import { IUser } from "../interfaces/User";
const userSchema = new Schema({
strategy: {
type: String,
enum: ["local", "facebook", "google"]
},
email: {
type: String,
lowercase: true
},
password: {
type: String
},
userId: {
type: String
}
});
const User = mongoose.model<IUser>("user", userSchema);
Now when I am trying to use:现在,当我尝试使用时:
const user :IUser= User.findOne({email});
if(!user){
done(null, false)
}
user.isValidPassword(password);
It says " TS2740: Type 'DocumentQuery<IUser | null, IUser, {}>' is missing the following properties from type 'IUser': email, password, strategy, userId, and 53 more."它说“TS2740:类型'DocumentQuery <IUser | null,IUser,{}>'缺少'IUser'类型的以下属性:email,密码,策略,用户ID和另外53个。”
If I try to remove 'IUser' from const user:IUser= User.findOne({email});
如果我尝试从
const user:IUser= User.findOne({email});
. . It doesnt let me use
user.isValidPassword(password);
它不允许我使用
user.isValidPassword(password);
And I dont want to use any
type for user.而且我不想为用户使用
any
类型。
You should query the user
document using await Model.findOne()
statement, see Model.findOne() .您应该使用
await Model.findOne()
语句查询user
文档,请参阅Model.findOne() 。
It will return the user
with the type IUser | null
它将返回类型为
IUser | null
的user
。 IUser | null
. IUser | null
。
Then, you can call the Instance methods - user.isValidPassword(password)
.然后,您可以调用实例方法-
user.isValidPassword(password)
。
An working example:一个工作示例:
user.ts
: user.ts
:
import { Document, Schema, model } from 'mongoose';
interface IUser extends Document {
email: string;
password: string;
strategy: string;
userId: string;
isValidPassword(password: string): boolean;
}
const userSchema = new Schema({
strategy: {
type: String,
enum: ['local', 'facebook', 'google'],
},
email: {
type: String,
lowercase: true,
},
password: {
type: String,
},
userId: {
type: String,
},
});
const User = model<IUser>('user', userSchema);
export { User, IUser };
main.ts
: main.ts
:
import { IUser, User } from './user';
async function main() {
const email = 'teresa.teng@gmail.com';
const password = '123';
const user: IUser | null = await User.findOne({ email });
if (!user) {
return;
}
user.isValidPassword(password);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.