📜  orm for postgres node js - Javascript(1)

📅  最后修改于: 2023-12-03 15:03:25.569000             🧑  作者: Mango

ORM for Postgres with Node.js - Javascript

Introduction

When building applications that require persistent storage, developers need to interact with a database. Typically, they use raw SQL queries to interact with the database and retrieve data. However, this approach can be complex, prone to SQL injection attacks, and difficult to maintain.

To solve these challenges, developers can opt for an ORM - Object-Relational Mapping. An ORM is a programming technique that maps objects to the underlying database stores. It allows developers to interact with the database by using more convenient and readable methods, instead of writing SQL queries manually.

In this article, we will explore an ORM for Postgres with Node.js - Javascript.

Prerequisites

Before we dive into the ORM itself, we need to have the following prerequisites installed:

  1. Node.js
  2. Postgres
  3. A code editor of your choice
ORM for Postgres - Sequelize.js

Sequelize.js is a popular ORM for Postgres with Javascript - Node.js. It is a promise-based ORM that supports transactions, eager-loading, and various database relationships such as one-to-one, one-to-many, and many-to-many. It also supports various authentication schemes such as JSON Web Tokens (JWT), Basic Auth, OAuth, and Passport.

Installation

To install Sequelize.js, use the following command:

npm install sequelize pg pg-hstore
Setting up a Connection

To use Sequelize, we need to set up a connection to our Postgres database. We can create a sequelize instance and pass in the connection parameters:

const {Sequelize} = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'postgres',
  host: 'localhost',
  port: 5432
});
Defining Models

Once we have set up a connection, we need to define our models. A model represents a table in the database and defines its attributes. For example, we can define a User model as follows:

const {DataTypes} = require('sequelize');

const User = sequelize.define('User', {
  firstName: {
    type: DataTypes.STRING,
    allowNull: false
  },
  lastName: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      isEmail: true
    }
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false
  }
});
Syncing Models

After defining our models, we need to synchronize them with the database. Sequelize will create the necessary tables in the database based on our model definitions. We can do this using the sync method:

sequelize.sync({force: true})
  .then(() => {
    console.log('Database synced');
  })
  .catch((err) => {
    console.error(err);
  });
CRUD Operations

Once our models are defined and synchronized, we can use Sequelize to perform CRUD (Create, Read, Update, Delete) operations on our data.

Create Operation

To create a new record, we can instantiate a new model and call the save method:

const user = User.build({
  firstName: 'John',
  lastName: 'Doe',
  email: 'johndoe@example.com',
  password: 'password'
});

user.save()
  .then(() => {
    console.log('User created');
  })
  .catch((err) => {
    console.error(err);
  });

Read Operations

To retrieve data from the database, we can use various Sequelize query methods such as findAll, findOne, and findByPk. For example, to retrieve all users, we can use the findAll method:

User.findAll()
  .then((users) => {
    console.log(users);
  })
  .catch((err) => {
    console.error(err);
  });

Update Operation

To update a record, we can first retrieve it and then call the save method:

User.findOne({where: {id: 1}})
  .then((user) => {
    user.firstName = 'Jane';
    user.lastName = 'Doe';
    return user.save();
  })
  .then(() => {
    console.log('User updated');
  })
  .catch((err) => {
    console.error(err)
  });

Delete Operation

To delete a record, we can retrieve it and then call the destroy method:

User.findOne({where: {id: 1}})
  .then((user) => {
    return user.destroy();
  })
  .then(() => {
    console.log('User deleted');
  })
  .catch((err) => {
    console.error(err)
  });
Conclusion

Sequelize.js is a powerful ORM for Postgres with Javascript - Node.js that provides a simpler and more convenient way to interact with the database. It supports various database relationships and authentication schemes and allows you to perform CRUD operations with ease.

In this article, we covered the basics of Sequelize.js, including setting up a connection, defining models, syncing models, and performing CRUD operations. We hope this article serves as a useful introduction to Sequelize.js and helps you get started in building your application with ease and confidence.