What is
Sequelize
Object Relational Mapping tool/library for JavaScript.
No need to write any SQL code.
Automatically Mapping to our model.
Mainly offers ->
- Models - ex- User, Product
- Instance -> const user= User.build()
- Queries -> User.findAll()
- Associations ->User.hasMany(Product)
Official Docs - >docs.sequelizejs.com
Installing Sequelize
npm install --save
sequelize (Required to be installed
mysql2 package)
1. Connection Setup
In databse.js->
const Sequelize = require("sequelize");
const sequlize = new Sequelize("node-first", "root", "", {
dialect: "mysql",
host: "localhost",
});
module.exports = sequlize;
2. Create a model
const Sequalize = require("sequelize");
const sequalize = require("../helper/database");
const Product = sequalize.define("product", {
id: {
type: Sequalize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
},
title: Sequalize.STRING,
price: {
type: Sequalize.DOUBLE,
allowNull: false,
},
ImageUrl: Sequalize.STRING,
description: {
type: Sequalize.STRING,
allowNull: false,
},
});
module.exports = Product;
3. Add configuration in App.js to automatically create tables
const sequelize = require("./helper/database");
//sequalize.sync()
//look all the models
you defined & create appropriate tables
sequelize
.sync()
.then((res) => {
console.log(res);
app.listen(3000);
console.log("Server running at http://127.0.0.1:3000/");
})
.catch((err) => {
console.log(err);
});

0 Comments