无法访问mongoose schema静态方法 - typescript

时间:2017-11-14 15:32:57

标签: node.js mongodb typescript express mongoose

我遇到的问题如下 - 有一个名为“findByToken()”的方法,它在模型中定义,并在userSchema中实现为静态方法。

在我的应用程序的另一部分,我无法使用以下方法访问该方法: User.findByToken(令牌) - 你可以帮我这个吗?似乎无法在任何地方找到答案。

import mongoose = require('mongoose');
import validator = require('validator');
import jwt = require('jsonwebtoken');

interface IUser {
  email: string,
  password: string,
  token: any[],
  generateAuthToken(): () => any
}

interface IUserModel extends IUser, mongoose.Document{
  findByToken: (token: any) => any;
  findByCredentials: (email: string, password: string) => any
}

let userSchema = new mongoose.Schema({
  email: {
      type: String,
      required: true,
      minlength: 1,
      trim: true,
      unique: true,
      validate: {
          validator: validator.isEmail,
          message: '{VALUE} is not a valid email'
      }
  },
  password: {
      type: String,
      required: true,
      minlength: 6
  },
  tokens: [{
      access: {
          type: String,
          required: true
      },
      token: {
          type: String,
          required: true
      }
  }]
});

userSchema.statics.findByToken = function(token: string) {
  let User = this; //entire model is binded with .this
  let decoded: any;

  try{
    decoded = jwt.verify(token, 'My Secret');
  } catch(e) {
      return Promise.reject('rejected');
  }

  return User.findOne({
    _id: decoded._id,
    'tokens.token': token,
    'tokens.access': 'auth'
  });
};


let User = mongoose.model<IUserModel>('User', userSchema);

export = User;

我如何称呼静态方法:

import User = require('./../models/user');
import express = require("express");

/*
tsconfig.json:
   "strict": true     will enfore types for req, res, next - etc
*/


//creating our auth private middleware
let authenticate = (req: express.Request, res: express.Request, next: express.Request) => {
    let token = req.header('x-auth');

    //custom model method
    User.findByToken(token).then((user) => {
        // if(!user){
        //     return Promise.reject(); //sends you directly into catch
        // }

        // req.user = user;
        // req.token = token;
        // next();

    }).catch((e) => {
        res.status(401).send();
    });

}

User.find

export = authenticate;

1 个答案:

答案 0 :(得分:0)

let User = mongoose.model<IUserModel>('User', userSchema);

应为:

let User = mongoose.model<IUser, IUserModel>('User', userSchema);