我正在我的应用程序中构建登录模块,这是我第一次使用TypeScript,所以我不知道如何处理这个问题。
我有一个控制器来处理登录和用户模型,我将把我的代码粘贴到下面。
在用户模型文件中,我有静态函数来处理登录内容,而我的应用程序崩溃了。
我遇到错误,类型'Model‘上不存在'login’属性
因此,如果有人知道这里发生了什么,请帮助我=]
import express, {Request, Response} from 'express'
import ErrorHandler from '../app/Handlers/ErrorHandler';
import { User } from '../model/User';
export const signup_post = async (req: Request, res: Response) => {
let {email, password} = req.body
try{
const user = await User.create({
email,
password
})
res.status(201).json({ user: user.email });
}
catch(err){
const errors = ErrorHandler.handleErrors(err);
res.status(400).json({ errors });
}
}
export const login_post = async (req: Request, res: Response) => {
let {email, password} = req.body
try {
const user = await User.login(email, password);
user.save();
}
catch (err) {
console.log(err)
const errors = ErrorHandler.handleErrors(err);
res.status(400).json({ errors });
}
}
import mongoose, { mongo } from 'mongoose';
import bcrypt from 'bcrypt';
import validator from 'validator'
const userSchema = new mongoose.Schema({
email: {
type: String,
required: [true, 'Please enter an email'],
unique: true,
lowercase: true,
validate: [validator.isEmail, 'Please enter a valid email'],
},
password: {
type: String,
required: [true, 'Please enter an password'],
minlength: [6, 'Minimum password length is 6 characters']
},
})
interface User {
email: string;
password: string;
}
userSchema.pre<User>('save', async function (next) {
this.password = this.password + "1"
next();
})
// static method to login user
userSchema.statics.login = async function(email, password) {
const user = await this.findOne({ email });
if(user) {
const auth = await bcrypt.compare(password, user.password);
if(auth) {
return user;
}
throw Error('incorrect password')
}
throw Error('incorrect email');
}
export const User = mongoose.model('user', userSchema)
发布于 2021-05-13 22:28:33
所以,你应该只使用接口来描述你的模型。例如:
// instead of 'interface User'
export interface UserDocument {
email: string;
password: string;
}
export interface UserModel extends mongoose.Model<UserDocument> {
login(email: string, password: string): UserDocument;
}
...
const User: UserModel = mongoose.model<UserDocument, UserModel>("user", userSchema);https://stackoverflow.com/questions/67519896
复制相似问题