Sequelize is a popular ORM (Object/Relational Mapper) that can be used with SQL databases like PostgreSQL, MySQL, SQLite, and Microsoft SQL Server. In this guide, I’ll show how to get started with Sequelize in a Node.js application.
1. Installation: First, you need to install Sequelize and the database specific dialect. For use with MySQL, you would run the following command.
\`\`\` npm install —save sequelize mysql2 \`\`\`1. Setting Up Sequelize: After installing Sequelize and the dialect, you can set up sequelize by importing it and passing the database details to the constructor as shown below.
\`\`\`javascript const Sequelize = require(‘sequelize’); const sequelize = new Sequelize(‘database’, ‘username’, ‘password’, { host: ‘localhost’, dialect: ‘mysql‘ }); \`\`\`1. Models: Data in Sequelize is often handled using models. You create a model by calling `sequelize.define` method. For example, let’s define a User model.
\`\`\`javascript const User = sequelize.define(‘User’, { // attributes firstName: { type: Sequelize.STRING, allowNull: false }, lastName: { type: Sequelize.STRING } }); \`\`\` This would create a `users` table with `firstName` and `lastName` columns in the database.1. Syncing Models: After defining models, you need to synchronize them with your database using `sequelize.sync` method.
\`\`\`javascript sequelize.sync().then(() => { console.log(‘Tables have been created’); }).catch(error => console.log(‘This error occurred’, error)); \`\`\`1. Inserting Data: You can insert data into your table using `create` method.
\`\`\`javascript User.create({ firstName: ‘John’, lastName: ‘Doe‘ }).then(user => { console.log(user.toJSON()); }); \`\`\`1. Querying Data: You can use `findAll`, `findOne` and other querying methods provided by Sequelize to fetch data.
\`\`\`javascript User.findAll({ where: { firstName: ‘John‘ } }).then(users => { console.log(users); }); \`\`\` Here is how you can query a single user. \`\`\`javascript User.findOne({ where: { firstName: ‘John‘ } }).then(user => { console.log(user); }); \`\`\`1. Updating Data: You can update data in your table using `update` method.
\`\`\`javascript User.update({ lastName: ‘Smith’ }, { where: { firstName: ‘John‘ } }).then(() => { console.log(‘updated’); }); \`\`\`1. Deleting Data: You can delete data from your table using `destroy` method.
\`\`\`javascript User.destroy({ where: { firstName: ‘John‘ } }).then(() => { console.log(‘deleted’); }); \`\`\`This was a very brief introduction to using Sequelize, make sure to check the [official documentation](https://sequelize.org/v5/index.html) for more in-depth guidelines and functionalities.