How to return only specific attributes when using Sequelize Create method
With a quick read through the docs, it seems attributes
is only mentioned within queries like:
Model.findAll({
attributes: { exclude: ['baz'] }
});
(http://docs.sequelizejs.com/manual/tutorial/querying.html#attributes)
If you want to exclude password
with create
, you could do something like:
let user = await User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
}, {
fields: ['firstName', 'lastName', 'email']
});
(http://docs.sequelizejs.com/manual/tutorial/instances.html#creating-persistent-instances)
I see in the document, you can't exclude attributes when you create a model. Only exclude when you find a model.
I suggest:
async create(req, res)
{
try {
let user = await User.create({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
});
delete user["password"];//delete field password
console.log("USER: ", user);
res.status(201).send(user.toJSON());
}
catch (error) {
res.status(500).send(error)
};
}
Try overloading Sequelize Model class with your desired functionality. For example, run following code once during application bootstrap:
import {Model} from 'sequelize';
const toJSON = Model.prototype.toJSON;
Model.prototype.toJSON = function ({attributes = []} = {}) {
const obj = toJSON.call(this);
if (!attributes.length) {
return obj;
}
return attributes.reduce((result, attribute) => {
result[attribute] = obj[attribute];
return result;
}, {});
};
After that, you can use your code as usual, but with an attributes
option:
User.toJSON({attributes: ['name', 'etc...']})
.