Connect app to SQL database
npm install --save mysql2
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
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));
// 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()
来源:51CTO
作者:fwu11
链接:https://blog.csdn.net/weixin_42552135/article/details/100691233