首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型'Model<any,any,any>‘上不存在属性’login

类型'Model<any,any,any>‘上不存在属性’login
EN

Stack Overflow用户
提问于 2021-05-13 21:15:13
回答 1查看 114关注 0票数 0

我正在我的应用程序中构建登录模块,这是我第一次使用TypeScript,所以我不知道如何处理这个问题。

我有一个控制器来处理登录和用户模型,我将把我的代码粘贴到下面。

在用户模型文件中,我有静态函数来处理登录内容,而我的应用程序崩溃了。

我遇到错误,类型'Model‘上不存在'login’属性

因此,如果有人知道这里发生了什么,请帮助我=]

代码语言:javascript
复制
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 });
      }
}

代码语言:javascript
复制
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)

EN

回答 1

Stack Overflow用户

发布于 2021-05-13 22:28:33

所以,你应该只使用接口来描述你的模型。例如:

代码语言:javascript
复制
// 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);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67519896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档