Databases - SQL

 

 SQL vs NoSQL
 

 

Connect app to SQL database

npm install --save mysql2

  Connection setup

const mysql = require('mysql2');

// connection pool
// manage multiple connections (multiple queries) simultaneously.
const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    database: 'node-complete',
    password:'Meiting5'
});

module.exports = pool.promise();

execute sql queries

db.execute('')

 

Sequelize

An object-relational mapping library

sequelize works with Promises

it does all the heavy lifting, all the SQL code behind the scenes for us and maps it into javascript objects with convenience methods which we can call to execute that behind the scenes SQL code so that we never have to write SQL code on our own.

 

npm install --save sequelize

 Connection setup

const Sequelize = require("sequelize");

const sequelize = new Sequelize("node-complete", "root", "Meiting5", {
  dialect: "mysql",
  host: "localhost"
});

module.exports = sequelize;

define model

const Product = sequelize.define('product',{
  id: {
    type:Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  title: Sequelize.STRING,

  price:{
    type: Sequelize.DOUBLE,
    allowNull: false
  },
  imageUrl: {
    type: Sequelize.STRING,
    allowNull: false
  },
  description: {
    type: Sequelize.STRING,
    allowNull: false
  }
});

Create table

sequelize
  .sync()
  .then(result => {
    app.listen(3000);
  })
  .catch(err => {
    console.log(err);
  });

Insert Data & create a product

exports.postAddProduct = (req, res, next) => {
  const title = req.body.title;
  const imageUrl = req.body.imageUrl;
  const price = req.body.price;
  const description = req.body.description;
  Product.create({
    title: title,
    price: price,
    imageUrl: imageUrl,
    description: description
  })
    .then(result => {
      console.log("Created Product");
    })
    .catch(err => {
      console.log(err);
    });
};

Retrieving data and find products

Product.findAll()
   .then(products => {
      res.render("shop/index", {
        prods: products,
        pageTitle: "Shop",
        path: "/"
      });
    })
    .catch(err => console.log(err));
// Product.findAll({where: {id: prodId}})

Product.findByPk(prodId)
    .then((product) => {
      res.render("shop/product-detail", {
        product: product,
        pageTitle: product.title,
        path: "/products"
      });
    })
    .catch(err => console.log(err));
// create if not exist, overwrite if not exist
product.save();

delete

Product.findByPk(prodId)
    .then(product => {
      return product.destroy();
    })
    .then(result => {
      console.log("DESTROYED");
      res.redirect("/admin/products");
    })
    .catch(err => console.log(err));

 Associations

 

// delete user, all product associated to the user gone
Product.belongsTo(User,{constraints: true, onDelete: 'CASCADE'});
User.hasOne(Cart);

create new associated object

// pass data cannot be inferred by sequelize
req.user.createProduct({
    title: title,
    price: price,
    imageUrl: imageUrl,
    description: description
  })
.getProducts()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值