gpt4 book ai didi

node.js - 如何在node-orm中定义虚拟属性?

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:04 25 4
gpt4 key购买 nike

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

作为一种解决方法,我尝试使用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-orm不支持​​这一点。我opened an issue希望将其添加为一项功能,但我还没有收到所有者的任何消息。

关于node.js - 如何在node-orm中定义虚拟属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com