【问题标题】:How can I define virtual properties in node-orm?如何在 node-orm 中定义虚拟属性?
【发布时间】:2014-08-24 23:09:40
【问题描述】:

我正在尝试使用 node-orm 设置用户表,并且我想将 passwordpasswordConfirmation 定义为虚拟属性(即:未保存,仅用于验证和计算)以及 @ 987654323@,实际上保存到数据库中。据我所知,这似乎没有内置到包中。

作为一种解决方法,我正在尝试使用Object.defineProperties,但我无处可去。这是我目前得到的相关代码。

var User = db.define('user', {
  id                : { type: 'serial', key: true },
  email             : { type: 'text', required: true, unique: true },
  encryptedPassword : { type: 'text', required: true, mapsTo: 'encrypted_password' }
}, {
  hooks: {
    beforeValidation: function (next) {
      this.encryptPassword(function (err, hash) {
        if (err) return next(err);

        this.encryptedPassword = hash;
        next();
      }.bind(this));
    }
  },

  validations: {
    password: [
      orm.enforce.security.password('6', 'must be 6+ characters')
    ],
    passwordConfirmation: [
      orm.enforce.equalToProperty('password', 'does not match password')
    ]
  },

  methods: {
    encryptPassword: function (callback) {
      bcrypt.hash(this.password, config.server.salt, callback);
    }
  }
});

Object.defineProperties(User.prototype, {
  password: {
    writable: true,
    enumerable: true
  },
  passwordConfirmation: {
    writable: true,
    enumerable: true
  }
});

然后我尝试通过以下方式创建用户:

var params = require('params');  // https://github.com/vesln/params

app.post('/register', function (req, res, next) {
  req.models.user.create([ userParams(req.body) ], function (err, users) {
    // post-create logic here
  });
});

function userParams(body) {
  return params(body).only('email', 'password', 'passwordConfirmation');
};

我遇到的问题是当调用bcrypt.hash 方法时,this.password 的值是undefined,导致它抛出这个错误:

{ [Error: data and salt arguments required]
  index: 0,
  instance: 
   { id: [Getter/Setter],
     email: [Getter/Setter],
     encryptedPassword: [Getter/Setter] } }

似乎password 属性没有通过我的create 调用设置,所以我假设这是因为 node-orm2 没有传递自定义属性值,或者我已经定义了属性错误(这可能是因为我之前没有真正使用过Object.defineProperties)。

我做错了什么,和/或是否有另一种我在谷歌搜索中找不到的方法?谢谢!

【问题讨论】:

    标签: node.js orm virtual-attribute node-orm2


    【解决方案1】:

    在挖掘代码之后,发现 node-orm 不支持这一点。我opened an issue 希望将其添加为一项功能,但我没有收到所有者的任何消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      相关资源
      最近更新 更多