A database

1 What is a database?

A database is a warehouse that organizes, stores, and manages data according to data structures

2 Why?

Our programs are run in memory, and once the program is finished or the computer is powered down, the data in the program is lost. Therefore, we need to persist the data of some programs to the hard disk to ensure the security of data, and the database is the best choice of data persistence, database is the warehouse of data storage.

3 Database classification

1. Relational Database (RDBS)

MySQL (lightweight and free, new version charges, but still offers the old version), Oracle (stable, expensive, huge), DB2 (between the two), SQL Server(easy to operate, currently rarely used)…

Features: Close relationship, are tables

Advantages:

1. Easy to maintain: table structure and consistent format

2. Easy to use: SQL is universal and can be used for complex queries

3. Advanced queries: Can be used for very complex queries between one table and multiple tables

Disadvantages:

1. Poor read and write performance, especially efficient read and write of massive data

2, there is a fixed table structure, lack of flexibility

3, high concurrent read and write requirements, for traditional relational database, disk I/O is a big bottleneck

2 Non-relational Database (NoSQL)

MongoDB, Redis…

Features: Loose relationships, documentation, key-value pairs

Advantages:

1 Flexible format: Data can be stored in key or value formats

2 fast: NoSQL can be memory as a carrier, and relational databases can only use hard disk

3 Easy to use: The NOSQL database is easy to deploy

Disadvantages:

1 Does not support SQL and costs a lot to learn and use

2 does not support transactions

3 Complex query statements are too complicated

Transaction: atomic, indivisible, such as transfer, you deduct some money, the other party to add some money

Two mongo

1 introduction of directing

MongoDB is a database system designed for rapid development of Internet Web applications.

MongoDB is designed to be minimal, flexible, and part of the Web application stack

The data model of MongoDB is document-oriented. The so-called document is a structure similar to Json. It is easy to understand that the MongoDB database stores various Json (BSON).

2 install the mongo

1 Installation Procedure

2 Start the MongoDB service

  1. Add environment variables and add the bin directory of MongoDB to pathCopy the code
  2. Create the following folder in the root directory of drive CCopy the code

C:\data\db

  1. Open a command line window and type Mongod to start the database serverCopy the code
  2. Open a new command line window and type Mongo to start the database clientCopy the code

Port number: Any application must run on a certain port

Port number: 1-65535. It is not recommended to use 1-199. These are reserved for the system

Common port numbers:

Port 21: FTP file transfer service

22 Port: indicates the SSH port

23: Indicates the TELNET terminal emulation service

3306: default port number of Mysql

Port 27017: default port of the MongoDB instance

3 the mongo server

1) The server is responsible for creating the database on the computer. To use the database, you need to start the server first

2) MongoDB default port number 27017

A can specify a port number with a –port

B The port number must be larger than or equal to 65535

C The port number used by other services cannot be used

3) By default, the MongoDB database will be placed in the data/ DB directory in the root directory of drive C

A can specify the directory of the database with the –dbpath directive

Combined use:

​ mongod –dbpath C:\users\web –port 12345

The command window for starting the service cannot be closed

4 the mongo client

1) We manage the database through the client

2) Use Mongo to start the client

3 Configure the MOngoDB database as a Windows service

1) Create the following folder in the root directory of drive C

c:\data\log

C:\data\db

2) Add a configuration file to the MongoDB installation directory

Directory: C: Program Files\MongoDB\Server\3.2

File: mongod. CFG

3) Open the command window as the administrator

4) Run the following command

Sc. exe create MongoDB binPath= "\"C:\Program Files\MongoDB\Server\3.2\bin\ god. Exe \" --service --config= "C:\Program Files\MongoDB\Server\3.2\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"

  1. Start the system server and start the MongoDB serviceCopy the code
  2. If the service cannot be started, enter the following command in the administrator command line windowCopy the code

sc delete MongoDB

  1. Repeat Step 1Copy the code

For relational databases:

EXcel file —- database

Sheet sheet —- table

Column header —- field —— Some fields that uniquely identify a piece of data are called primary keys

A row —– a data line

For non-relational databases:

EXcel file —- database

Sheet TAB —- Collection

Column header —- field

A line —– a document

Use of MongoDB

1 introduction

1.1 Database

A database is a repository in which collections can be stored.

1.2 Collection

Collections are similar to arrays in JS, where documents can be stored.

In plain English, a collection is a set of documents.

1.3 Document (Document)

The smallest unit in a document database, what we store and manipulate are documents.

Like objects in JS, each piece of data in MongoDB is a document.

2 use

2.1 Basic Commands

  1. Display all databasesCopy the code

show dbs

​ show databases

  1. Switch to the specified databaseCopy the code

Use Database name

  1. Displays the current databaseCopy the code

db

  1. Deleting the current databaseCopy the code

db.dropDatabase()

  1. Displays all collections in the current databaseCopy the code

show collections

  1. Delete current collectionCopy the code

db.collection.drop()

7) Insert a document into the students set of the current database

db.students.insert()

2.2 Operation Commands

In MongoDB, neither the database nor the collection need to be created; the collection and database are created automatically when we insert a document into the collection or database for the first time.

  1. Insert documents into the collectionCopy the code

db.. insert(doc)

Such as: db. Stus. Insert ({name: “sunwukong”, the age: 18})

  1. Query documents in the collectionCopy the code

db.. find()

Such as: db. Stus. The find ()

2.3 DATABASE CRUD

The query url: docs.mongodb.com/manual/refe…

  1. Insert a document into the collection (create)Copy the code

Db.collection.insert ({}) inserts a document into the collection

Db.collection.insertone ({}) inserts a document into the collection

Db.collection.insertmany ({},{}) inserts multiple documents into the collection

  1. Query documents in collections (read)Copy the code

Db.collection.find (query criteria, [projection]) queries all documents in the collection that match the criteria, always returning an array of document objects

Projection: Filter out unwanted data and keep only the data you want to show

Such as:

Db.collection. find({name:’ grade ‘}, {stu_id:1,grade:1}

Common operators:

\1. Operators: >, >=, <, <=,! Corresponding: = “gt”, “gt”, “gt” and “gte,” “lt”, “lt”, “lt”, “lte $ne”,”

For example: db. Collection. The find ({age: {$lt: 19}})

\2. Operators: “or”,” or”,”or”, “in”,” $nin”

For example: db. Collection. The find ({age: {$in: [18] 3}})

​ db.collection.find({$or:[{age:18},{age:19}]})

Db. Collection. The find ({age: {$nin: [19]}})

\3. Regular expressions

For example: db. Collection. The find ({name: ^ T /})

​ \4. “$where”

Such as:

db.collection.find({$where:function(){

​ return this.name==’zhangsan’&&this.age==18;

}})

Db.collection. findOne(query condition) Finds only the first occurrence of data

  1. Modify documents in a collection (update)Copy the code

Db.collection.update (query criteria, new document, [configuration object]) Modifies or replaces one or more documents

// The update replaces the entire document object, but the _id is not affected

db.collection.update({name:’zhangsan’},{age:19})

// Use $set to change the specified contents

db.collection.update({name:’zhangsan’},{$set:{age:19}})

// Modify multiple document objects, match multiple Zhangsan, replace all zhangsan’s age with 19

db.collection.update({name:’zhangsan’},{$set:{age:19}},{multi:true})

Add:

Db. Collection. UpdateOne ()

Db. Collection. UpdateMany ()

  1. Delete a document from a collection (delete)Copy the code

Db.collection. remove(query criteria) Removes all (or the first) documents that meet the criteria

Use of Mongoose

1 introduction

Mongoose is an object Document Model (ODM) library that further optimizes and encapsulates Node’s native MongoDB module with additional functionality.

MongoDB is a well-known package for helping developers connect to MongoDB on the Node platform

Why Mongoose?

Want to in node platform, more simple, convenient, safe, stable operation of MongoDB

2 advantages

  1. You can create a Schema structure for your documentCopy the code
  2. You can validate objects/documents in the modelCopy the code
  3. Data can be converted to an object model through type castingCopy the code
  4. Middleware can be used to apply business logic hooksCopy the code
  5. Easier than Node's native MongoDB driverCopy the code

3 Core Objects

3.1 Schema

A Schema object that allows you to constrain collections

3.2 the Model

Model object, equivalent to a collection in a database, through which you can operate on the collection

3.3 the Document

Document object, which corresponds to the document in the database, through which you can read the information of the document, but also can carry out various operations on the document

4 Connecting a Database

Let mongoose = the require (' mongoose ') / / 1 connect to the database mongoose. Connect (' mongo: / / localhost: 27017 / test ', { UseNewUrlParser :true,// Uses a new URL parser to resolve security issues. UseUnifiedTopology: Mongoose.connection. on('open',function(eor){if(eor){console.log(' database connection failed ')}else{ Console. log(' database connection successful ') //3 Operating database console.log(' operating database ')}})Copy the code
let mongoose=require('mongoose') mongoose.set('useCreateIndex',true); / / USES a new index create, / / 1 connect to the database mongoose. Connect (' mongo: / / localhost: 27017 / test ', {useNewUrlParser: true, / / use the new url interpreter, UseUnifiedTopology: Mongoose.connection. on('open',function(eor){if(eor){console.log(' database connection failed ')}else{ Console. log(' database connected successfully ') //3 Operate database //1 Hire a security guard to help you ---- introduce Schema object let Schema = Mongoose TeachersRule =new Schema({stu_id:{type:String,// restrict to String require:true,// restrict to unique:true,// restrict to unique), Name :{type:String,// restrict :String require:true,// restrict: mandatory}, age:{type:Number,// restrict :String require:true,// restrict: mandatory}, // restrict :{type:Number,// restrict :String require:true,// restrict: mandatory}, Hoppy :[String],// Limit the function array, And each item in the array is string info: Schema. The Types, Mixed, the date / / receiving all Types: {type: date, default: the date, now (), require: true, / / restricted to mandatory}, enable_flag:{ type:String, TeacherModel = Mongoose. Model ('teacher',teachersRule)// Used to generate a set of corresponding model objects Teachermodel. create({stu_id:'003', name:' ZHS ', age:23, hoppy:[' eat ',' sing '], info:66644},function(err,data){if(! Err) console.log(data) else console.log(err)}) // query operation //find method, 1 returns an array, even a single piece of data is wrapped in an array. Teachermodel.find ({name:'q'},function(err,data){if(! Err) console.log(data) else console.log(err)}) Teachermodel. findOne({name:'q'},{age:1,_id:0},function(err,data){if(! Err) console.log(data) else console.log(err)}) // Update operation Update Deprecated available updateOne updateMany teacherModel.updateOne({name:'qwx'},{age:6},function(err,data){ if(! Teachermodel.deletemany ({age:16},{age:6},function(err,data){if(! err) console.log(data) else console.log(err) }) } })Copy the code

5 mongoose modular

Var mongoose = require("mongoose"); var mongoose = require("mongoose"); const DB_NAME='mongoose_test' const PORT='27017' const IP='localhost' function aaa(callback){ mongoose.connect("mongodb://${IP}:${PORT}/${DB_NAME}"); Mongoose.connection. on("open",function (eor){if(eor){console.log(' connection failed ') callback(' connection failed '); }else{console.log(' database connection succeeded ') callback(); }}); } model.exports=aaa; Var mongoose = require("mongoose"); var Schema = mongoose.Schema; Var stuSchema = new Schema({name:String, age:Number, gender:{type:String, default:" female "}, address:String}); Var Student = mongoose. Model (" Student ",stuSchema); Module. exports = Student; Test.js var db = require("./tools/db"); Var student = require("./models/student"); db(function(err){ if(err) console.log(err); Else {Student. Create ({name:" Erlang god ", age:"48", gender:" male ", address:" small god "},function (err) {if(! Err){console.log(" insert successfully "); }}); }})Copy the code