Several ways to persist node

  • CSV comma-separated Values xx; Xx JSON object serialization {aa:’11’} => “{aa:’11’}”
  • The database
    1. Mysql relational
    2. Directing a document type
    3. Redis key value relationships

The file system

// Store and read through local JSON object serialization
const fs = require("fs");

function get(key) {
  fs.readFile("./db.json".(err, data) = > {
    const json = JSON.parse(data);
    console.log(json[key]);
  });
}
function set(key, value) {
  fs.readFile("./db.json".(err, data) = > {
    // May be empty file, set to empty object
    const json = data ? JSON.parse(data) : {};
    json[key] = value; / / set the value
    // Write the file again
    fs.writeFile("./db.json".JSON.stringify(json), err= > {
      if (err) {
        console.log(err);
      }
      console.log("Write successful!");
    });
  });
}

// The command line interface part
const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.on("line".function(input) {
  const [op, key, value] = input.split("");

  if (op === 'get') {
    get(key)
  } else if (op === 'set') {
    set(key, value)
  } else if(op === 'quit'){
    rl.close();
  }else {
    console.log('No such operation'); }}); rl.on("close".function() {
  console.log("End of program");
  process.exit(0);
});

// Command line input after the test starts
set aa bb
// Write succeeded!
get aa
//bb
Copy the code

mysql

/ / installation
npm i sequelize mysql2 -S
/ / use:
(async() = > {const mysql = require('mysql2/promise')

    // Connection configuration
    const cfg = {
        host: "localhost".user: "root".password: "xxx".// Change it to your password
        database: "xxxx" // Make sure the database exists
    }

    const connection = await mysql.createConnection(cfg)

    let ret = await connection.execute(` CREATE TABLE IF NOT EXISTS test ( id INT NOT NULL AUTO_INCREMENT, message VARCHAR(45) NULL, PRIMARY KEY (id)) `)
    console.log('create', ret)

    ret = await connection.execute(` INSERT INTO test(message) VALUES(?) `['ABC'])
    console.log('insert:', ret)


    ret = await connection.execute(` SELECT * FROM test `)
    console.log(JSON.stringify(ret[0]))
    // console.log(ret[1])

    connection.end()

})()    

Copy the code

Object Relation Mapping (ORM) based on Promise – Sequelize

/ / installation
npm i sequelize sequelize -S
/ / use:
(async() = > {/ / 1: N relationship
    const Sequelize = require("sequelize");

    // Establish a connection
    const sequelize = new Sequelize("kaikeba"."root"."xxxx", {
        host: "xxxxx".dialect: "mysql"});const Fruit = sequelize.define("fruit", { name: Sequelize.STRING });
    const Category = sequelize.define("category", { name: Sequelize.STRING });
    Fruit.FruitCategory = Fruit.belongsToMany(Category, {
        through: "FruitCategory"
    });

    // Insert test data
    sequelize.sync({ force: true }).then(async() = > {await Fruit.create(
            {
                name: "Banana".categories: [{ id: 1.name: "Tropical" }, { id: 2.name: "Temperate"}]}, {include: [Fruit.FruitCategory]
            }
        );
        // many-to-many joint query
        const fruit = await Fruit.findOne({
            where: { name: "Banana" }, // Specify conditions, fields, and so on through
            include: [{ model: Category, through: { attributes: ['id'.'name']}}}); })}) ()Copy the code

Common Create Commands


// Avoid generating redundant time fields
timestamps: false

// Resolve a unique database migration problem
id: { 
    type: Sequelize.DataTypes.UUID, 
    defaultValue: Sequelize.DataTypes.UUIDV1,
    primaryKey: true
},
Copy the code

One-to-many, many-to-one relationship

const Sequelize = require('sequelize');
module.exports.initModel = async sequelize => {
    // Create table user
  const User = sequelize.define('user', { name: Sequelize.STRING });
    // Create an item list
  const Product = sequelize.define('product', { title: Sequelize.STRING });
  Product.belongsTo(User); // End 1 establishes the relationship
  User.hasMany(Product); // Establish a relationship on the N end
  
  return { User, Product }
}
Copy the code