Blog>
Snippets

Performing Database Operations with Sequelize

Execute non-blocking database queries using the Sequelize ORM with promise chaining.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'sqlite',
  storage: './database.sqlite'
});
This code imports the Sequelize package and creates an instance of Sequelize which is used for connecting to a database. In this case, SQLite is used, but Sequelize also supports other databases like PostgreSQL, MySQL, and MSSQL.
const User = sequelize.define('User', {
  username: Sequelize.STRING,
  birthday: Sequelize.DATE
});
Defines a User model with a username and birthday field, mapping to a table in the database.
sequelize.sync()
  .then(() => User.create({
    username: 'janedoe',
    birthday: new Date(1980, 6, 20)
  }))
  .then(jane => {
    console.log(jane.toJSON());
  })
  .catch(error => {
    console.error('Failed to create a new user:', error);
  });
Synchronizes the model with the database (creating the table if it doesn't exist) and then creates a new record in the User table. Afterwards, it logs the new user or an error if the operation fails.
User.findAll()
  .then(users => {
    console.log('All users:', JSON.stringify(users, null, 2));
  })
  .catch(error => {
    console.error('Failed to retrieve users:', error);
  });
Retrieves all users from the User table and logs them, or logs an error if the operation fails.
User.update({ username: 'jdoe' }, {
  where: { id: 1 }
})
  .then(() => {
    console.log('User updated successfully.');
  })
  .catch(error => {
    console.error('Failed to update user:', error);
  });
Updates a user with a specific id (in this case id: 1) in the User table and informs about success or failure.
User.destroy({
  where: { id: 1 }
})
  .then(() => {
    console.log('User deleted successfully.');
  })
  .catch(error => {
    console.error('Failed to delete user:', error);
  });
Deletes a user with a specific id (in this case id: 1) from the User table and informs about success or failure.