javascript - Mongoose 模型静态/方法不保存 "this"中的值

标签 javascript node.js mongodb mongoose passport.js

我试图用mongodb用户模型实现passport js身份验证。现在如您所见,我已经在用户模型上创建了一个方法。因此,当我在用户的实例上应用此方法时,我希望“this”保存所有用户对象。但在本例中,这种情况并未发生。以下是一个工作代码,但我传递了一个附加变量以使其工作。但我不想那样做。我哪里出错了?

下面是用于登录的 Passport 配置文件

var passport = require('passport');
var User = require('../models/users');
var LocalStrategy = require('passport-local').Strategy;

passport.serializeUser((user, done)=>{
  done(null, user.id);
});

passport.deserializeUser((id, done)=>{
  User.findById(id, (err, user)=>{
    done(err, user);
  });
});

passport.use('local.signin', new LocalStrategy({
usernameField: 'email', passwordField: 'password', passReqToCallback: true
},(req, email, password, done) => {
User.findOne({email:email}, (err, user) => {
    if (err){ return done(err)}
    if (!user){return done(null, false, {message:'This email is not registered'})}
      if (!user.validatePassword(password, user.password)){
/**********************************************/
//is this field user.password really necessary?
/**********************************************/
          return done(null, false, {message: 'Authentication Failed'})
      } else {
          return done(null, user);
      }
  });
}));

用户模型如下:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');

var userSchema = new Schema({
  salutation: {type: String, required: false},
  firstname: {type: String, required: true},
  lastname: {type: String, required: false},
  email: {type: String, required: true},
  password: {type: String, required: true}
});

userSchema.methods.validatePassword = (password, x) => {
  console.log(this); //this is returning null
  return bcrypt.compareSync(password, x);
/*********************************************************/
//I was excepting this.password to work instead of using x
/*********************************************************/
}

userSchema.methods.myCourses = (userId) => {
  console.log(this.enrolledFor);
}

module.exports = mongoose.model('User', userSchema);

最佳答案

ECMA2015 标准也称为 ES6 允许使用箭头函数,这些函数从上层上下文继承其上下文。

解决方案是使用常规函数语法。

userSchema.methods.validatePassword = function (password, x) {
  console.log(this); //this is returning null
  return bcrypt.compareSync(password, x);
/*********************************************************/
//I was excepting this.password to work instead of using x
/*********************************************************/
}
----------

Article about arrow functions

Arrow functions – also called “fat arrow” functions, from CoffeeScript (a transcompiled language) are a more concise syntax for writing function expressions. They utilize a new token, =>, that looks like a fat arrow. Arrow functions are anonymous and change the way this binds in functions.

Arrow functions make our code more concise, and simplify function scoping and the this keyword. They are one-line mini functions which work much like Lambdas in other languages like C# or Python. (See also lambdas in JavaScript). By using arrow function we avoid having to type the function keyword, return keyword (it’s implicit in arrow functions), and curly brackets.

关于javascript - Mongoose 模型静态/方法不保存 "this"中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41238735/

相关文章:

node.js - 使用 telnet 测试 Node websockets

javascript - 为什么 ngRepeat 没有按预期生成有序列表?

用于弹出类别列表的 JavaScript 不起作用

ruby - 用于实时/并行 HTTP 爬虫的良好库/平台?

node.js - 在不同端口上运行前端和后端

Mongodb - 从查找中获取对象而不是数组

node.js - lwip.open 在 mongoose findOne 之后不起作用

arrays - MongoDB - 如何验证嵌套数组项是否包含在同一文档的另一个嵌套数组项中?

javascript - 如何使数据表按标签搜索

javascript - AJAX 获取数据,回发并再次获取