首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript/Mongoose错误:类型模型上不存在findUser

Typescript/Mongoose错误:类型模型上不存在findUser
EN

Stack Overflow用户
提问于 2021-03-26 09:40:14
回答 1查看 64关注 0票数 0

我有以下代码。我想实现身份验证使用MongoDB,mongoose,express使用typescript。我有一个打字问题。我尝试为findUser声明类型(可能不正确),但没有解析。有什么建议吗?

model.ts

代码语言:javascript
复制
import mongoose, { Schema, Document } from 'mongoose';
import bcrypt from 'bcrypt';

export interface IUser extends Document {
  username: string;
  password: string;
}

const userSchema: Schema = new Schema({
  username: {
    type: String,
    unique: true,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
});

// tslint:disable-next-line: only-arrow-functions
userSchema.statics.findUser = async function (username, password) {
  const user = await User.findOne({ username });
  if (!user) {
    return;
  }

  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) {
    return;
  }
  return user;
};

userSchema.pre<IUser>('save', async function (next) {
  const user = this;
  if (user.isModified('password')) {
    user.password = await bcrypt.hash(user.password, 8);
  }
  next();
});

const User = mongoose.model<IUser & Document>('User', userSchema);
export default User;

auth.ts (路由)错误:属性'findUser‘在类型'Model’上不存在。.ts(2339)

代码语言:javascript
复制
import express from 'express';
import User from '../models/user-model';
const router = express.Router();

declare module 'express-session' {
  // tslint:disable-next-line: interface-name
  export interface SessionData {
    user: { [key: string]: any };
  }
}

router.post('/signin', async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findUser(email, password);
  if (user) {
    req.session.user = user._id;
    res.json({
      message: 'You are successfully login',
      auth: true,
    });
  } else {
    res.json({
      message: 'Unable to login',
      auth: false,
    });
  }
});



export = router;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-26 10:58:50

您可以在描述模型本身的mongoose.model()方法上设置second generic

这里我们包含了Model<IUser>的所有属性,还添加了您的自定义函数。

代码语言:javascript
复制
type UserModel = Model<IUser> & {
    findUser: (username: string, password: string) => Promise<IUser | undefined>;
}

IUser确定此模型中文档的类型,而UserModel确定模型的类型。

代码语言:javascript
复制
const User = mongoose.model<IUser, UserModel>('User', userSchema);

现在,该方法的类型是已知的。这里的user获取类型IUser | undefined

代码语言:javascript
复制
const user = await User.findUser('joe', 'abcd');

Typescript Playground Link

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66809902

复制
相关文章

相似问题

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