Nodejs Road-MongoDB&MySQL


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    
                {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}


    • 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:

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


#This command defaults to connect to the local MongoDB service

Sign out:

#Enter exit in connection state to exit the connection

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:

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:

Official Guidelines:

Official API documentation:

  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 => 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.
      // 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({
              required:true //Express username Must have
      //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({
              console.log("Save failed")
              console.log("Successful Preservation")
    • query

      • Query all

                console.log("Query failure")
      • Conditionally query all

            username:"zs"  //That's the condition.
                console.log("Query failure")
      • Query individually on condition

            username:"zs"  //That's the condition.
                console.log("Query failure")
    • Delete data

      • Delete all eligible data

                console.log("Delete failed")
                console.log("Successful deletion")
      • Delete the first eligible data

        }, function (err) {
            if (err){
                return handleError(err)
            // deleted at most one User document


      • Delete a data based on id

    • Update data

      • Update all items according to conditions

      • Follow the new one according to the specified conditions

      • Update one based on id

                console.log("Update failed")
                console.log("Update Successful")



1. Official Reference

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
// 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

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