在初始化期间设置Bookshelf属性会在未定义的“this”上引发错误

时间:2015-06-02 06:29:30

标签: bcrypt bookshelf.js

我在Bookshelf模型中看到关于'this'的奇怪行为并且感到难过。我正在尝试使用“保存”事件上的钩子来哈希密码。但是,如果我尝试在'this'上获取/设置一个属性,它会抱怨'this'未定义:

'use strict';

var DB = require('../config/db'),
    _ = require('underscore'),
    str = require('underscore.string'),
    Base = require('./base'),
    Promise = require('bluebird'),
    bcrypt = Promise.promisifyAll(require('bcrypt'));

var User = DB.Model.extend({
  tableName: 'users',
  hasTimestamps: ['createdAt', 'updatedAt'],

   // convert snake_case to camelCase
  parse: function(attrs) {
    return _.reduce(attrs, function(memo, val, key) {
      memo[str.camelize(key)] = val;
      return memo;
    }, {});
  },

  // convert camelCase to snake_case
  format: function(attrs) {
    return _.reduce(attrs, function(memo, val, key) {
      memo[str.underscored(key)] = val;
      return memo;
    }, {})
  },

  initialize: function() {
    this.on('saving', this.hashPassword, this);
  },

  hashPassword: function() {
    return bcrypt.genSaltAsync(10).then(function(salt){
      return bcrypt.hashAsync(this.get('password'), salt);
    }).then(function(hash){
      this.set({'password':hash});
    });
  }
});

module.exports = User;

当我尝试保存用户模型时,我看到了以下堆栈跟踪:

Debug: internal, implementation, error 
    Error: TypeError: Cannot call method 'get' of undefined
    at Object.exports.create (/usr/src/app/node_modules/boom/lib/index.js:21:17)
    at Object.exports.internal (/usr/src/app/node_modules/boom/lib/index.js:254:92)
    at Object.exports.badImplementation (/usr/src/app/node_modules/boom/lib/index.js:290:23)
    at null.<anonymous> (/usr/src/app/routes/users.js:31:20)
    at tryCatcher (/usr/src/app/node_modules/bluebird/js/main/util.js:24:31)
    at Promise._settlePromiseFromHandler (/usr/src/app/node_modules/bluebird/js/main/promise.js:454:31)
    at Promise._settlePromiseAt (/usr/src/app/node_modules/bluebird/js/main/promise.js:530:18)
    at Promise._settlePromises (/usr/src/app/node_modules/bluebird/js/main/promise.js:646:14)
    at Async._drainQueue (/usr/src/app/node_modules/bluebird/js/main/async.js:177:16)
    at Async._drainQueues (/usr/src/app/node_modules/bluebird/js/main/async.js:187:10)
    at Async.drainQueues (/usr/src/app/node_modules/bluebird/js/main/async.js:15:14)
    at process._tickDomainCallback (node.js:486:13)

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这有用吗?

hashPassword: function() {

    var self = this;

    return bcrypt.genSaltAsync(10).then(function(salt) {
        return bcrypt.hashAsync(self.get('password'), salt);
    }).then(function(hash) {

        self.set({
            'password': hash
        });

    });
}