Skip to content

JS and TS

toJSON usage

When there is a need to access a sequelize model's property, this can be achieved by using directly the key of the property e.g. modelName.propertyName. There is no need to use the toJSON method for retrieving a property or for returning the response e.g.

javascript
const email = user.toJSON().email;

// or
return {
    user: user.toJSON(),
};
const email = user.toJSON().email;

// or
return {
    user: user.toJSON(),
};

Sequelize models have a toJSON method that is used to convert the model to a JSON object. This method is used automatically by the res.json method to convert the response to JSON and by the JSON.stringify method to convert the object to a string.