Nodejs the road (four) - MongoDB & MySQL

A, MongoDB

1.1 Overview

  1. MongoDB is a distributed file storage based database. Written by C ++ language. Designed to provide scalable, high-performance data storage solution for WEB applications. MongoDB is a product with function between relational databases and non-relational databases, non-relational database functions among the richest and most like a relational database.

  2. Relational databases and non-relational databases

    • Relational databases: there is a relationship between the table and the table

      • All relational data may need to pass sqlto manipulation language

      • All relational database before operations need to design the table structure

      • All relational database support constraints:

        • only

        • Primary key

        • Defaults

        • non empty

    • Non-relational databases

      • Some non-relational database is key-valuefor children, no table

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

        • Database -> Database

        • Data Sheet -> set (array)

        • Table records -> Document Object

      • MongoDB does not require design table structure, which means you can store any data entered, no structural say

  3. The basic concepts of MongoDB database

    • There can be multiple databases at the database --mongodb

    • Set - A database can have multiple collections (equivalent in MySQL table)

    • Documentation - A collection can have multiple documents (the equivalent of table records in MySQL)

  4. MongoDB storage structure:
    {
         // database     
        QQ: {   
             // set 
            Users: [
                 @ document 
                {name: " Joe Smith " , Age: 15 }, 
                {name: " John Doe " , Age: 16 }, 
                {name: " Wang Mazi " , Age: . 17 }, 
                {name: " Mr. Liu five " , Age: 18 is }, 
                {name: " Zhaolao six " , Age: . 19 } 
                ...... 
            ], 
            Products: [ 
                
            ] 
            ...... 
        }, 
        taobao: { 
            
        }, 
        baidu: { 
            
        } 
        ...... 
    }

             note:

    • Document structure is very flexible, there is no limit
    • MongoDB is very flexible, not like the MySQL as create databases, tables, design table structure. When you need to insert data, you only need to specify which set of operations which database to it. All by MongoDB to help you auto-complete collection of building a database built this thing children 

1.2 Installation

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

note:

  • Remember to configure the environment variables

  • Enter the   mongod --version test is successfully installed

1.3 database startup and shutdown mongodb

  • start up:

    mongod --dbpath = directory path data storage

    note:

    • MongoDB will be in the db directory, but this will not take the initiative to create the data directory data directory store. When we first started mongodb, you need to manually create at the root data\dbdirectory. Here we must note that the data directory should be placed in the root directory (such as: C:\or D:\so on, for example, I was put C:\data\dbunder)

    • When you first start mongodb, execute the command: mongod --dbpath "C:\data\db"When the back and then start mongodb, directly execute the command: mongodyou can

    • mongod --dbpath command is to create a database file storage location, you need to determine the location of the database files are stored when you first start mongodb service, otherwise the system will not automatically create, start, will not succeed.

  • stop:
    In the open service console, direct + Ctrl C to stop 
    or open the service console directly off can   

1.4 database connections and exit mongodb

connection:

# The command default MongoDB service to connect the machine 
mongo

drop out:

# Type exit to leave the connection in the connected state 
exit

1.5 Basic Commands

  • show dbs: View to display the desired database

  • db: View the current operation of the database

  • use 数据库名称: Switch to the specified database (if there is no will New)

  • as follows:

  

1.6 How to operate in MongoDB database in Node

1.6.1 use the official MongoDBpackage to operate

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

1.6.2 Using a third party to operate the MongoDB database mongoose

Third-party packages mongoose: the official MongoDB-based mongodbpackage once again made packaging

Official website: https://mongoosejs.com/

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

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

  1. Started

    • installation:

      npm i mongoose
    • Examples demo:

      // official reference template 
      const = Mongoose the require ( 'Mongoose' ); 
      
      // connected MongoDB database 
      mongoose.connect ( 'MongoDB: // localhost: 27017 / Test', {useNewUrlParser: to true }); 
      
      // create a model that in the design of the database 
      // MongoDB is a very dynamic and flexible, just in the code will be able to design a database 
      // Mongoose this package can make your design process becomes very simple to write 
      const Cat = mongoose.model ( 'Cat ', {name: String}); // Although Cat here uppercase, lowercase but generated all cats name 
      
      // instantiate a Cat 
      const = Kitty new new Cat ({name:' Zildjian ' }); 
      
      // persistent example preservation Kitty 
      kitty.save () then (() = > console.log ( 'meow')).;
  2. Official Guide

    • Schema Design Model release

      var Mongoose = the require ( 'Mongoose' ) 
      
      var the Schema = mongoose.Schema 
      
      
      // 1. connection database 
      // specified database connection need not be present, when you are automatically inserted into the first data is created 
      mongoose.connect ( ' MongoDB: // localhost / Test ' ) 
      
      // 2. design the structure set (table structure) 
      // field name is the name of the attribute table structure 
      // object constraint is to ensure data integrity, do not have dirty data 
      var userSchema = new new the Schema ({ 
          username: { 
              type: String, 
              required: to true  // represents username must be 
          }, 
          password: { 
              type: String, 
              required: to true 
          }, 
          In Email: {
              of the type: String 
          } 
      
        }); 
      
      // 3. The structure of the collection published as model 
      // mongoose.model approach is a framework used to publish a Model 
      // The first parameter: passing a string to uppercase singular noun represents your database name 
      //           Mongoose will automatically generate a set of strings capitalized nouns plural name in lowercase. Here, for example, User set name users will eventually become 
      // second parameter: the Schema architecture 
      // Return Value: model constructor 
      var User = mongoose.model ( 'User' , userSchema) 
      
      // 4. When the model has been constructed after the function, you can use this constructor set of data users do whatever (CRUD)
    • Increased data

      var admin = new User({
          username:"admin",
          password:"123456",
          email:"[email protected]"
      })
      
      admin.save(function(err,ret){
          if(err){
              console.log("保存失败")
          }else{
              console.log("保存成功")
              console.log(ret)
          }
      })
    • Inquire

      • All inquiries

        User.find(function(err,ret){
            if(err){
                console.log("查询失败")
            }else{
                console.log(ret)
            }
        })
      • Query by the conditions of all

        User.find ({ 
            username: "ZS"   // This is the condition 
        }, function (ERR, RET) {
             IF (ERR) { 
                console.log ( "Query failed" ) 
            } the else { 
                console.log (RET) 
            } 
        })
      • Single query by the conditions

        User.findOne ({ 
            username: "ZS"   // This is the condition 
        }, function (ERR, RET) {
             IF (ERR) { 
                console.log ( "Query failed" ) 
            } the else { 
                console.log (RET) 
            } 
        })
    • delete data

      • Delete all qualified data

        User.remove ({ 
            username: "ZS" 
        }, function (ERR, RET) {
             IF (ERR) { 
                console.log ( "deletion failed" ) 
            } the else { 
                console.log ( "deleted successfully" ) 
                console.log (RET ) 
            } 
        })
      • Delete the first qualifying data

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

        or

        User.findOneAndRemove(conditions,[options],[callback])
      • To delete a data according to id

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

      • Update all according to the conditions

        User.update(conditions,doc,[options],[callback])
      • According to specified conditions with a new

        User.findOneAndUpdate([conditions],[update],[options],[callback])
      • According to a id update

        User.findByIdAndUpdate ( '5d32fa6bac0b39270c256225' , { 
            password: "123" 
        }, function (ERR, RET) {
             IF (ERR) { 
                the console.log ( "Update Failed" ) 
            } the else { 
                the console.log ( "Update Success" ) 
            } 
        })

         

Two, MySQL

1. official reference

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

2. Install

npm install mysql

3. Reference demo

var MySQL = the require ( 'MySQL' ); 

// 1. Create a connection 
var Connection = mysql.createConnection ({ 
  Host: 'localhost' , 
  User: 'the root' , 
  password: '123' , 
  Database: 'Students.' 
}); 
 
// 2. connect database 
connection.connect (); 
 
// 3. perform data operations 
connection.query ( 'the SELECT * `users` the FROM', function (error, Results, Fields) {
   IF (error) the throw error; 
  Console. log ( 'Solution of The IS:' , Results); 
});

//--------- all CRUD query methods which operate at ------------------------------ -------- 
// ------------- increase data ------------------------- 
// connection.query ( 'the INSERT the INTO Users the VALUES (null, "ADMIN", "123456")', function (error, Results, Fields) { 
//        IF (error) the throw error; 
//        the console.log ( 'of The IS Solution: ', Results); 
//      }); 

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

note:

  • To install the MySQL advance, and open the MySQL service
  • For MySQL, create a database connection of tables and fields set up in advance

Guess you like

Origin www.cnblogs.com/FHC1994/p/11228032.html