Nodejs Road-MongoDB&MySQL

MongoDB

1.1 Overview

  1. MongoDB is a database based on distributed file storage. Written in C++ language. The aim is to provide a scalable and high performance data storage solution for WEB applications. MongoDB is a product between relational database and non-relational database, which has the most abundant functions and resembles relational database.

  2. Relational and non-relational databases

    • Relational databases: relationships between tables

      • All relational data can be manipulated by sql

      • All relational databases need to design table structure before operation

      • All relational databases support constraints:

        • Unique

        • Primary key

        • Default values

        • Nonempty

    • Non-relational database

      • Some non-relational databases are key-value pairs without tables

      • MongoDB is a non-relational database that looks most like a relational database

        • Database - > Database

        • Datasheet - > Set (Array)

        • Table Record - > Document Object

      • MongoDB does not need to design a table structure, that is, it can store data in it at will. There is no such thing as structure.

  3. Basic concepts of MongoDB database

    • Database - There can be multiple databases under mongodb

    • Collections - A database can have multiple collections (equivalent to tables in MySQL)

    • Documents - A collection can have multiple documents (equivalent to table records in MySQL)

  4. MongoDB's storage structure:
    {
        //data base    
        qq:{   
            //aggregate
            users:[
                //File
                {name:"Zhang San",age:15},
                {name:"Li Si",age:16},
                {name:"Wang Ma Zi",age:17},
                {name:"Liu Laowu",age:18},
                {name:"Zhao Laoliu",age:19}
                ......
            ],
            products:[
                
            ]
            ......
        },
        taobao:{
            
        },
        baidu:{
            
        }
        ......
    }

Attention:

    • Document structure is flexible without any restrictions
    • MongoDB is very flexible and does not need to create databases, tables, and design table structures like MySQL. When you need to insert data, you just need to specify which set of operations to which database. Everything is done automatically by MongoDB.

1.2 Installation

64-bit download address: https://www.mongodb.com/download-center/community

Be careful:

  • Remember to configure environment variables

  • Enter mongod --version to test whether the installation was successful

1.3 Start and close the mongodb database

  • Start:

    mongod --dbpath = data storage directory path

    Be careful:

    • MongoDB stores the data directory in the DB directory, but this data directory will not be created on its own initiative. When we first started mongodb, we needed to manually create the data DB directory in the root directory. Note here that the data directory should be placed under the root directory (e.g. C: or D: etc.) and mine under C: data db).

    • When you start mongodb for the first time, execute the command: mongod -- dbpath "C: data db", and then when you start mongodb, execute the command directly: mongod.

    • The mongod --dbpath command is the storage location for creating database files. When starting the mongodb service for the first time, it is necessary to determine the storage location of database files. Otherwise, the system will not create automatically and the start-up will be unsuccessful.

  • Stop it:
    On the console that opens the service, direct Ctrl+C stops
    Or close the console that opens the service directly.

1.4 Connect and exit mongodb database

Connect:

#This command defaults to connect to the local MongoDB service
mongo

Sign out:

#Enter exit in connection state to exit the connection
exit

1.5 Basic Order

  • show dbs: View the database you want to display

  • db: View the currently operating database

  • use database name: switch to the specified database (if not new)

  • As follows:

  

1.6 How to operate MongoDB database in Node

1.6.1 uses the official MongoDB package to operate

Download address: https://github.com/mongodb/node-mongodb-native

1.6.2 Use third-party mongoose to operate the MongoDB database

Third-party package mongoose: MongoDB-based official mongodb package is encapsulated again

Official website: https://mongoosejs.com/

Official Guidelines: https://mongoosejs.com/docs/guides.html

Official API documentation: https://mongoosejs.com/docs/api.html

  1. start

    • Installation:

      npm i mongoose
    • Example demo:

      // Official Reference Template
      const mongoose = require('mongoose');
      
      // Connect MongoDB data base
      mongoose.connect('mongodb://localhost:27017/test', {useNewUrlParser: true});
      
      // To create a model is to design a database
      // MongoDB It's dynamic and very flexible. It just needs to design the database in the code.
      // mongoose This package can make your design writing process very simple.
      const Cat = mongoose.model('Cat', { name: String });//Although here Cat It's capitalized, but it generates lowercase cats Collection name
      
      //item base Cat
      const kitty = new Cat({ name: 'Zildjian' });
      
      // Persistence preservation Kitty Example
      kitty.save().then(() => console.log('meow'));
  2. Official Guidelines

    • Design Schema Publishing Model

      var mongoose = require('mongoose')
      
      var Schema = mongoose.Schema
      
      
      // 1.Connect to the database
      // The database that specifies the connection does not need to exist, and it will be created automatically when you insert the first data.
      mongoose.connect('mongodb://localhost/test')
      
      // 2.Designing Collective Structures (Table Structures)
      // The field name is the attribute name in the table structure.
      // The purpose of constraints is to ensure the integrity of data without dirty data.
      var userSchema = new Schema({
          username:{
              type:String,
              required:true //Express username Must have
          },
          password:{
              type:String,
              required:true
          },
          email:{
              type:String
          }
      
        });
      
      //3.Publishing the collection structure as a model
      // mongoose.model The method is to publish an architecture as one model
      // First parameter: Pass in a capital NOUN word number string to represent your database name
      //          mongoose The string of uppercase nouns is automatically generated into the set name of the lowercase plural. For example, here's the User Eventually it will become users Collection name
      // Second parameter: architecture Schema
      // Return value: model constructor
      var User = mongoose.model('User', userSchema)
      
      // 4.When you have a model constructor, you can use this constructor pair users Data in a collection is what you want (add, delete, modify, check)
    • Adding data

      var admin = new User({
          username:"admin",
          password:"123456",
          email:"admin@admin.com"
      })
      
      admin.save(function(err,ret){
          if(err){
              console.log("Save failed")
          }else{
              console.log("Successful Preservation")
              console.log(ret)
          }
      })
    • query

      • Query all

        User.find(function(err,ret){
            if(err){
                console.log("Query failure")
            }else{
                console.log(ret)
            }
        })
      • Conditionally query all

        User.find({
            username:"zs"  //That's the condition.
        },function(err,ret){
            if(err){
                console.log("Query failure")
            }else{
                console.log(ret)
            }
        })
      • Query individually on condition

        User.findOne({
            username:"zs"  //That's the condition.
        },function(err,ret){
            if(err){
                console.log("Query failure")
            }else{
                console.log(ret)
            }
        })
    • Delete data

      • Delete all eligible data

        User.remove({
            username:"zs"
        },function(err,ret){
            if(err){
                console.log("Delete failed")
            }else{
                console.log("Successful deletion")
                console.log(ret)
            }
        })
      • Delete the first eligible data

        User.deleteOne({ 
            username:"admin"
        }, function (err) {
            if (err){
                return handleError(err)
            }
            // deleted at most one User document
        })

        or

        User.findOneAndRemove(conditions,[options],[callback])
      • Delete a data based on id

        User.findByIdAndRemove(id,[options],[callback])
    • Update data

      • Update all items according to conditions

        User.update(conditions,doc,[options],[callback])
      • Follow the new one according to the specified conditions

        User.findOneAndUpdate([conditions],[update],[options],[callback])
      • Update one based on id

        User.findByIdAndUpdate('5d32fa6bac0b39270c256225',{
            password:"123"
        },function(err,ret){
            if(err){
                console.log("Update failed")
            }else{
                console.log("Update Successful")
            }
        })

         

MySQL

1. Official Reference

https://www.npmjs.com/package/mysql

2. Installation

npm install mysql

3. Reference demo

var mysql      = require('mysql');

// 1.Create a connection
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '123',
  database : 'students'
});
 
// 2.Connect to the database
connection.connect();
 
// 3.Perform data operations
connection.query('SELECT * FROM `users`', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results);
});

// ---------All additions, deletions and modifications are checked. query Method inside operation--------------------------------------
// -------------Adding data-------------------------
// connection.query('INSERT INTO users VALUES(null,"admin","123456")', function (error, results, fields) {
//       if (error) throw error;
//       console.log('The solution is: ', results);
//     });

// 4.Close the connection
connection.end();

Be careful:

  • To install MySQL in advance and open MySQL service
  • For MySQL, tables and fields for creating connected databases need to be set up in advance

Tags: PHP MongoDB Database Mongoose MySQL

Posted on Mon, 22 Jul 2019 05:51:24 -0700 by bznutz