How To Use Sequelize with Node.js and SQL

In this blog post, we’ll guide you through the process of building a blog application using Node.js, SQLite, and Sequelize. We’ll cover setting up the server, defining API endpoints for blog posts, and implementing step-by-step database migrations to evolve your database schema.

Why Use SQLite, Sequelize, and Node.js?

  • SQLite: SQLite is a serverless, self-contained, and lightweight database engine, making it an excellent choice for small to medium-sized web applications.
  • Sequelize: Sequelize is a Node.js Object-Relational Mapping (ORM) library that simplifies database interactions, including database migrations.
  • Node.js: Node.js is a versatile JavaScript runtime that allows you to build server-side applications with ease.

Prerequisites

Before we begin, ensure you have Node.js and npm (Node Package Manager) installed on your system. You can download them from the official Node.js website.

Getting Started

1. Initialize Your Node.js Project

Start by creating a new directory for your blog project and set up your Node.js project:

mkdir blog-app
cd blog-app
npm init -y` 

2. Install Dependencies

Install the necessary packages: express for the server, sequelize for database migrations, and sqlite3 for SQLite.

npm install express sequelize sqlite3 sequelize-cli

3. Configure the Database

Modify your Sequelize configuration to use SQLite. Create a config.json file with the following content:

{
  "development": {
    "dialect": "sqlite",
    "storage": "db.sqlite"
  }
}

4. Initialize Sequelize

Initialize Sequelize in your project:

npx sequelize-cli init

This command generates essential folders and files for your project, including the configuration, models, and migrations.

5. Create a Blog Model

Generate a model for your blog posts:

npx sequelize-cli model:generate --name BlogPost --attributes title:string,content:text

This command creates a BlogPost model with title and content attributes.

6. Create and Apply Migrations

Migrations help you manage changes to your database schema over time. Generate a migration file and apply it to create the initial BlogPost table:

npx sequelize-cli db:migrate

7. Setting Up the Server and Endpoints

Now, let’s set up the server and define API endpoints for your blog posts. Create a new file, app.js:



const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

const { BlogPost } = require('./models'); // Replace with your model path

app.get('/posts', async (req, res) => {
  const posts = await BlogPost.findAll();
  res.json(posts);
});

app.post('/posts', async (req, res) => {
  const { title, content } = req.body;
  const post = await BlogPost.create({ title, content });
  res.json(post);
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

8. Running the Server

Start your server by running:

node app.js

Your server is now running, and you can access the following API endpoints:

  • GET /posts: Retrieve all blog posts.
  • POST /posts: Create a new blog post.

9. Writing New Migrations

As your blog application evolves, you may need to modify the database schema. Create new migration files for each change using npx sequelize-cli migration:generate.

For example, to add an “author” column to your BlogPost model:

npx sequelize migration:generate --name blogpost_author
// In the migration file
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.addColumn('BlogPosts', 'author', {
      type: Sequelize.STRING,
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.removeColumn('BlogPosts', 'author');
  },
};

Apply the new migration with npx sequelize-cli db:migrate.

Conclusion

You’ve just built a blog application with SQLite, Sequelize, and Node.js. This real-world example covers setting up the server, defining API endpoints for blog posts, and implementing step-by-step database migrations. Use this as a foundation to build your own web applications and learn more about database migrations in Node.js.

Happy coding!

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post