我想configurate我的数据库,我想将数据返回给用户不包括一些sensetive数据,所以我添加instanceMethods命名toPublicJSON,使用一个命名函数挑从underscoreJS,但是当我使用这个功能(toPublicJSON)我遇到一个错误:即toPublicJSON不是功能sequelize instanceMethods
这是我的数据库configurat离子:
var bcrypt = require("bcrypt");
var _ = require("underscore");
module.exports = function(sequelize, DataType) {
return sequelize.define('users', {
email: {
type: DataType.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
salt: {
type: DataType.STRING
},
hassedPassword: {
type: DataType.STRING
},
password: {
type: DataType.VIRTUAL,
allowNull: false,
validate: {
len: [7, 100]
},
set: function(value) {
var salt = bcrypt.genSaltSync(10);
var hashed_password = bcrypt.hashSync(value, salt);
this.setDataValue('password', value);
this.setDataValue("salt", salt);
this.setDataValue("hassedPassword", hashed_password);
}
}
}, {
hooks: {
beforeValidate: function(user, option) {
if (typeof user.email == 'string')
user.email = user.email.toLowerCase();
}
},
instanceMethods:{
toPublicJSON: function() {
var json = this.toJSON();
return _.pick(json, 'id', 'email', 'createdAt', 'updatedAt');
}
}
});
}
我的代码:
app.post('/users',function(req,res){
var body=_.pick(req.body,"email","password");
db.users.create(body).then(function(user){
return res.send(user.toPublicJSON());
},function(e){
return res.status(400).json(e);
})
});
,这是错误:
如果定义了'toPublicJSON'为您Sequelize表的原型函数像我这样做是应该为你工作。你只需稍微调整一下你如何定义模型就可以了。 –
非常感谢:) – Zola
现在工作谢谢 – Zola