Reputation: 79
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.');
};
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.');
};
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);
};
Upvotes: 2
Views: 3429
Reputation: 193
Use Getter on your model and return undefined
password: {
type: DataTypes.STRING,
get() {
return undefined;
}
}
Upvotes: 0
Reputation: 2223
You can try using toJSON instance method to exclude attributes:
Model:
instanceMethods: {
toJSON: function () {
const userObj = Object.assign({}, this.dataValues);
delete userObj.password;
return userObj
}
}
Route file:
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.');
});
Upvotes: 2