When you work with Sequelize, you will often retrieve data using methods like .findOne() or .findAll(). These methods return Sequelize model instances, not the underlying data. Under the hood they are just JavaScript objects that represent the data in the database. These instances have additional methods and properties that allow you to manipulate the data and perform actions on it.
However, sometimes you may want to retrieve just the raw data object, without any of the model-specific properties or methods. This is where the { plain: true } option comes in handy. When you pass this option to the .get() method of a Sequelize instance, it will return only the raw data object, without any of the additional properties or methods.
Let’s look at an example to see how this works:
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'sqlite',
storage: './database.sqlite'
});
const User = sequelize.define('User', {
firstName: Sequelize.STRING,
lastName: Sequelize.STRING,
email: Sequelize.STRING
});
(async () => {
await sequelize.sync({ force: true });
// Create a user
const user = await User.create({
firstName: 'John',
lastName: 'Doe',
email: 'johndoe@example.com'
});
// Retrieve the user as a Sequelize instance
const userInstance = await User.findOne({ where: { id: user.id } });
console.log(userInstance);
// Output:
// User {
// dataValues: { id: 1, firstName: 'John', lastName: 'Doe', email: 'johndoe@example.com' },
// ...
// }
// Retrieve the user as a plain JavaScript object
const userData = userInstance.get({ plain: true });
console.log(userData);
// Output:
// { id: 1, firstName: 'John', lastName: 'Doe', email: 'johndoe@example.com' }
})();
In this example, we create a new user using the .create() method of the User model. We then retrieve the user using the .findOne() method and store the result in the userInstance variable. If we log this variable to the console, we can see that it is a Sequelize instance with additional properties and methods.
Next, we retrieve the user again using the .get() method with the { plain: true } option. This time, the method returns only the raw data object, without any of the additional properties or methods. We store this object in the userData variable and log it to the console.
As you can see, the userData variable contains only the raw data values of the user, without any of the additional properties or methods. This can be useful if you want to pass the data to another function or module that expects plain JavaScript objects, or if you want to serialize the data to JSON.
Is a method that lives on a single instance of a model. When using a method like .findAll(), this is going to return an array of model instances.
You will need to look through this array and run .get({plain:true}) on each of the model instances to remove torun them into raw data object.