Sequelize:不要在创建时返回密码 [英] Sequelize: Don't return password on Create
问题描述
当我使用 Sequelize 创建我的用户的新实例时,我会从数据库中获取完整的对象作为对 Create 的响应.我试图阻止 Sequelize 在创建时返回存储在我的用户表中的散列密码.
When I create a new instance of my User with Sequelize, I get the full object returned from the database as a response to the Create. I'm trying to prevent Sequelize from returning the hashed password stored in my User table on create.
exports.create = (payload, err, success) => {
db.user.create(payload).then(success).catch(err);
console.log('Created new user record.');
};
我尝试使用 exclude 属性,但返回完整对象.
I tried using the exclude property, but the full object returns.
exports.create = (payload, err, success) => {
db.user.create(payload, {
attributes: {
exclude: ['password']
}
}).then(success).catch(err);
console.log('Created new user record.');
};
我可以在我的 find 和 findAll 路由的属性中使用 exclude 属性,如下例所示,但我无法让它与我的 create 一起使用.
I am able to use the exclude property in attributes on my find and findAll routes like the example below, but I haven't been able to get it to work with my create.
exports.find = (payload, err, success) => {
db.user.find({
where: {
id: payload.id,
},
attributes: {
exclude: ['password']
}
}).then(success).catch(err);
console.log('Retrieved user record with id: ' + payload.id);
};
推荐答案
您可以尝试使用 toJSON 排除属性的实例方法:
You can try using toJSON instance method to exclude attributes:
型号:
instanceMethods: {
toJSON: function () {
const userObj = Object.assign({}, this.dataValues);
delete userObj.password;
return userObj
}
}
路由文件:
user.create(request.body, (err) => {
res.status(500).json(err);
console.log('Error creating new user.');
}, (data) => {
res.status(200).json(data.toJSON());
console.log('User created.');
});
这篇关于Sequelize:不要在创建时返回密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!