Database MongoDB; Object Document Model (ODM) library Mongoose

Database

  • ? A database is a warehouse that organizes, stores and manages data according to its data structure.
  • ? Our programs are all run in memory. Once the program finishes running or the computer is powered off, the data in the running program will be lost.
  • ? So we need to persist some program running data to the hard disk to ensure data security. The database is the best choice for data persistence.
  • ? To put it bluntly, a database is a warehouse for storing data.

Database classification

  • ? There are two main types of databases:
    • – Relational Database
      • ? MySQL, Oracle, DB2, SQL Server…
      • ? A relational database is full of tables
    • – Non-relational database
      • ? MongoDB, Redis…
      • ? Key-value pair database
      • ? document database MongoDB

Introduction to MongoDB

  • ? 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.
  • ? MongoDB’s data model is document-oriented. The so-called document is a structure similar to JSON. Simply understand that MongoDB stores various
    JSON. (BSON)

Download MongoDB

  • ? download link
    • – https://www.mongodb.org/dl/win32/
  • ? The even-numbered version of MongoDB is the stable version, and the odd-numbered version is the development version.
  • ? MongoDB does not support 32-bit systems well, so
    There is no support for 32-bit systems after version 3.2.

MongoDB installation




Start MongoDB

  • ? Add the MongoDB bin directory to the path

  • ? Create a data folder under the root directory of the C disk, and create a db folder under data

  • ? Open the CMD command line window and enter mongod

  • ? The 32-bit system starts for the first time:

    • – mongod –storageEngine=mmapv1
  • ? The following output appears

Specify port and path

  • ? Start MongoDB in the console
    • – mongod –dbpath path –port port number
    • – Example:
      • ? mongod –dbpath C:\Users\lilichao\Desktop\mongo\data\db –port 123
  • ? Note: The opened command line window cannot be closed

Configure the windows service of mongo

  • ? Create a mongod.cfg file in the 3.x directory of the server under the mongo installation directory, and add the following content
systemLog:
destination: file
path: c:\data\log\mongod.log
storage:
dbPath: c:\data\db
  • ? Open the console in administrator mode and enter the following command

sc.exe create MongoDB binPath=””mongo bin path\mongod.exe” –service –
config=”mongo path\mongod.cfg”” DisplayName=”MongoDB” start=”auto”

  • ? Delete service

sc delete MongoDB

Close MongoDB

  • ? Open a new command line window
  • ? Login server
    • – mongo
  • ? Switch admin user
    • – admin
  • ? Close the database
    • – db. shutdownServer()

Mongo Shell

  • ? Login mongo shell
    • – mongo
  • ? Order
    • – help syntax help
    • – use to change the database of the current operation
    • – show show the list according to the parameter
      • ?dbs Display a list of databases
      • ? collections displays the collections of the current database
      • ?profile Show system.profile entries longer than 1 millisecond
      • ? log[name] show the last segment of the login memory
  • – exit Exit the database
  • – load(script) load the js file db.auth(username, password) to authenticate in the current database

Three concepts

  • ? database
    • – A database is a warehouse in which collections can be stored.
  • ? collection
    • – A collection is similar to an array, and documents can be stored in the collection.
  • ? document
    • – The smallest unit in a document database, the content we store and manipulate is a document.

Basic concepts

  • ? document
    • – Similar to objects in JS, each piece of data in MongoDB is a document
  • ? collection
    • – A collection is a group of documents, that is, a collection is used to store documents
    • – Documents stored in collections can be of various types, with no format requirements
  • ? Multiple documents form a collection, and multiple collections form a database

Create database

  • ? use database name
    • – When using use, if the database exists, it will enter the corresponding database, if it does not exist, it will be created automatically
    • – Once in the database, you can use db to refer to the current library
  • ?db.collection.insert(documentation)
    • – Insert documents into the collection, or create the collection if it does not exist
  • ?db. createCollection()
    • – Create a new collection
  • ?db. collection. drop()
    • – delete collection

Addition, deletion, modification and query of documents

  • ? Insert document
    • – db.collection.insert()
  • ? query document
    • – db.collection.find()
  • ? Delete document
    • – db.collection.remove()
  • ? Modify the document
    • – db. collection. update()

Add document

  • ?db.collection.insert (document object)
    • – insert() can be used to add one or more documents to the collection, and can pass an object or an array.
    • – Objects or objects in an array can be added to the collection
    • – If the collection or database does not exist when adding, it will be created automatically
    • – The inserted document object will add the _id attribute by default, which corresponds to a unique id, which is the unique identifier of the document

Delete document

  • ?db. collection. remove()
    • – remove() can be used to remove the specified document object
    • – The method receives a query document as a parameter, and only documents that meet the criteria will be deleted
    • – Deleting data is permanent and cannot be undone
  • ?db. collection. drop()
    • – delete collection

Modify the document

  • ?db. collection. update()
  • ? Replace document
    • – You can pass two parameters in update(), one is the query document and the other is the new document, so that the documents that meet the conditions will be replaced by the new documents
    • – The third parameter of update() is used to specify whether to use upsert, the default is false
    • – The fourth parameter of update() is used to specify whether to modify multiple documents at the same time, the default is false

Modifier

  • ? Using update will replace the entire document, but in most cases we don’t need to do this
  • ? If you only need to update a part of the document, you can use the update modifier to do it.
  • ? We will learn the following modifiers
    • – $set,

      u

      no

      the s

      e

      t

      ,

      unset,

      unset, inc,

      p

      u

      the s

      h

      ,

      push,

      push, addToSet

the s

e

t

,

set,

set, unset

  • ? $set is used to specify the value of a field, if the field does not exist, it will be created.
  • ? grammar:
    • – db.test_coll.update(query object, {$set:update object});
  • ? $unset can be used to delete an unnecessary field in the document, the usage is similar to set.

$inc

  • ? $inc is used to increase the value of an existing key, or create a key if it does not exist
  • ? $inc can only be used for Number type values

Query documents

  • ? find(), findOne()
    • – MongoDB uses find() to query documents
    • – find() requires a query document as a parameter, if this parameter is not passed, all elements in the collection will be returned.
    • – Query conditions can be added to the query document in the form of key-value pairs
    • – Query conditions
      • ?

        l

        t

        ,

        lt,

        lt, lte,

        g

        t

        ,

        gt,

        gt, gte,

        no

        e

        ,

        ne,

        ne, or,

        i

        no

        ,

        in,

        in, nin,

        no

        o

        t

        ,

        not,

        not, exists, $and

Data

dept.json

{<!-- -->
  "_id" : ObjectId("5941f2bac1bc86928f4de49a"),
  "deptno" : 10.0,
  "dname" : "Finance Department",
  "loc" : "Beijing"
}
{<!-- -->
  "_id" : ObjectId("5941f2bac1bc86928f4de49b"),
  "deptno" : 20.0,
  "dname" : "office",
  "loc" : "Shanghai"
}
{<!-- -->
  "_id" : ObjectId("5941f2bac1bc86928f4de49c"),
  "deptno" : 30.0,
  "dname" : "Sales Department",
  "loc" : "Guangzhou"
}
{<!-- -->
  "_id" : ObjectId("5941f2bac1bc86928f4de49d"),
  "deptno" : 40.0,
  "dname" : "Operation Department",
  "loc" : "Shenzhen"
}

emp.json

{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4ac"),
  "empno" : 7369.0,
  "ename" : "Lin Chong",
  "job" : "staff",
  "mgr" : 7902.0,
  "hiredate" : ISODate("1980-12-16T16:00:00Z"),
  "sal" : 800.0,
  "depno" : 20.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4ad"),
  "empno" : 7499.0,
  "ename" : "Sun Erniang",
  "job" : "Sales",
  "mgr" : 7698.0,
  "hiredate" : ISODate("1981-02-19T16:00:00Z"),
  "sal" : 1600.0,
  "comm" : 300.0,
  "depno" : 30.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4ae"),
  "empno" : 7521.0,
  "ename" : "Hu Sanniang",
  "job" : "Sales",
  "mgr" : 7698.0,
  "hiredate" : ISODate("1981-02-21T16:00:00Z"),
  "sal" : 1250.0,
  "comm" : 500.0,
  "depno" : 30.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4af"),
  "empno" : 7566.0,
  "ename" : "Lu Junyi",
  "job" : "manager",
  "mgr" : 7839.0,
  "hiredate" : ISODate("1981-04-01T16:00:00Z"),
  "sal" : 2975.0,
  "depno" : 20.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b0"),
  "empno" : 7654.0,
  "ename" : "Pan Jinlian",
  "job" : "Sales",
  "mgr" : 7698.0,
  "hiredate" : ISODate("1981-09-27T16:00:00Z"),
  "sal" : 1250.0,
  "comm" : 1400.0,
  "depno" : 30.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b1"),
  "empno" : 7698.0,
  "ename" : "Ximen Qing",
  "job" : "manager",
  "mgr" : 7839.0,
  "hiredate" : ISODate("1981-04-30T16:00:00Z"),
  "sal" : 2850.0,
  "depno" : 30.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b2"),
  "empno" : 7782.0,
  "ename" : "Chai Jin",
  "job" : "manager",
  "mgr" : 7839.0,
  "hiredate" : ISODate("1981-06-08T16:00:00Z"),
  "sal" : 2450.0,
  "depno" : 10.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b3"),
  "empno" : 7788.0,
  "ename" : "Gongsun Sheng",
  "job" : "Analyst",
  "mgr" : 7566.0,
  "hiredate" : ISODate("1987-07-12T16:00:00Z"),
  "sal" : 3000.0,
  "depno" : 20.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b4"),
  "empno" : 7839.0,
  "ename" : "Song Jiang",
  "job" : "Chairman",
  "hiredate" : ISODate("1981-11-16T16:00:00Z"),
  "sal" : 5000.0,
  "depno" : 10.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b5"),
  "empno" : 7844.0,
  "ename" : "Yan Poxi",
  "job" : "Sales",
  "mgr" : 7698.0,
  "hiredate" : ISODate("1981-09-07T16:00:00Z"),
  "sal" : 1500.0,
  "comm" : 0.0,
  "depno" : 30.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b6"),
  "empno" : 7876.0,
  "ename" : "Li Kui",
  "job" : "staff",
  "mgr" : 7902.0,
  "hiredate" : ISODate("1987-07-12T16:00:00Z"),
  "sal" : 1100.0,
  "depno" : 20.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b7"),
  "empno" : 7900.0,
  "ename" : "Wu Song",
  "job" : "staff",
  "mgr" : 7782.0,
  "hiredate" : ISODate("1981-12-02T16:00:00Z"),
  "sal" : 950.0,
  "depno" : 10.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b8"),
  "empno" : 7902.0,
  "ename" : "Wu Yong",
  "job" : "Analyst",
  "mgr" : 7566.0,
  "hiredate" : ISODate("1981-12-02T16:00:00Z"),
  "sal" : 3000.0,
  "depno" : 20.0
}
{<!-- -->
  "_id" : ObjectId("5941f5bfc1bc86928f4de4b9"),
  "empno" : 7934.0,
  "ename" : "Lu Zhishen",
  "job" : "staff",
  "mgr" : 7782.0,
  "hiredate" : ISODate("1982-01-22T16:00:00Z"),
  "sal" : 1300.0,
  "depno" : 10.0
}

Introduction to Mongoose

  • ? Previously, we used the shell to complete various operations on the database. Most of the time during development, we needed to complete the operations on the database through programs.
  • ? And Mongoose is a module that allows us to operate MongoDB through Node.
  • ? Mongoose is an object document model (ODM) library, which further optimizes and encapsulates the native MongoDB module of Node, and provides more functions.
  • ? In most cases, it is used to apply structured schemas to a MongoDB collection, and provides benefits such as validation and type conversion

Benefits of mongoose

  • ? A schema structure (Schema) can be created for the document
  • ? Objects/documents in the model can be validated
  • ? Data can be converted to an object model by type conversion
  • ? Middleware can be used to apply business logic hooks
  • ? Easier than Node’s native MongoDB driver

New object

  • ? Mongoose provides us with several new objects
    • – Schema (schema object)
      • ? The Schema object definition constrains the document structure in the database
    • – Model
      • ? The Model object is used as a representation of all documents in the collection, which is equivalent to the collection in the MongoDB database
    • – Document
      • ? Document represents a specific document in the collection, which is equivalent to a specific document in the collection

Connect to MongoDB through mongoose

  • ? To use Mongoose, you must first install the mongoose package
    • –npm install mongoose
  • ? Load Mongoose
    • – const mongoose = require("mongoose")
  • ? Connect to the database
    • – mongoose.connect(“mongodb://address”)
    • – Address example: mongodb://127.0.0.1/mg_test
  • ? Disconnect
    • – mongoose. disconnect()

connection

  • ? Once the MongoDB database is connected, the underlying Connection object can be accessed through the conection property of the mongoose module.
  • ? The connection object is an abstraction of the database connection, which provides access to the object connection, the underlying Db object and the Model object representing the combination.
  • ? And you can monitor some events on the connection object to know the start and end of the database connection.
  • ? For example, the opening and closing of connections can be monitored through the open and close events.

Schema mode object

  • ? With Mongoose you must often define schemas.
  • ? Schemas define the fields and field types for the documents in the collection.
  • ? This is useful if your data is structured to support a schema.
  • ? To put it simply, a schema is a constraint on a document. With a schema, the fields in a document must conform to the requirements of the schema. Otherwise, normal operation will not be possible.

Definition pattern

  • ? Schemas define the fields and field types for the documents in the collection.
  • ? For each field in the schema, you need to specify a specific value type. The supported types are as follows:
    • – String
    • –Number
    • – Boolean
    • – Array
    • – Buffer
    • – Date
    • – ObjectId or Oid
    • – Mixed
  • ? You need to define a schema for each of the different document types you plan to use.

Create schema definition

  • ? The schema needs to be created through mongoose’s Schema property, which is a constructor.
    • – new Schema(definition, option)
      • ? definition (description mode)
      • ? options configuration object, defining the interaction with the collection in the database

options common options

  • ?autoIndex
    • – Boolean value, enable automatic indexing, default true
  • ?bufferCommands
    • – Boolean value, cache statements that cannot be executed due to connection problems, default true
  • ?capped
    • – Maximum number of documents in the collection
  • ? collection
    • – Specify the collection name of the application schema
  • ?id
    • – Boolean, whether there is an id handler applied to _id, default true
  • ?_id
    • – Boolean value, whether to automatically assign the id field, default true
  • ? strict
    • – Boolean value, objects that do not conform to the Schema will not be inserted into the database, the default is true

Model model object

  • ? Once the Schema object is defined, the Model object needs to be created through the Schema object.
  • ? Once the Model object is created, it will automatically establish a connection with the corresponding collection in the database to ensure that when the changes are applied, the collection has been created and has the appropriate index.
    Citation, and set the necessity and uniqueness.
  • ? The Model object is equivalent to the collection in the database, and the CRUD operation on the collection can be completed through the Model.
  • ? To create a model object, you need to use the model() method of mongoose. The syntax is as follows:
    • – model(name, [schema], [collection] , [skipInit])
      • ? The name parameter is equivalent to the name of the model, and you can use the name to find the model in the future.
      • ? schema is the created schema object.
      • ? collection is the name of the collection to be connected.
      • ? skipInit whether to skip initialization, the default is false.
  • ? Once you’ve compiled a Schema object into a Model object, you’re completely ready to start accessing, adding, deleting, updating, and deleting documents in the model. That is to say, with the model
    After that we can operate the database.

Methods of the Model object

  • ? remove(conditions, callback)
  • ? deleteOne(conditions, callback)
  • ?deleteMany(conditions, callback)
  • ?find(conditions, projection, options, callback)
  • ?findById(id, projection, options, callback)
  • ?findOne(conditions, projection, options, callback)
  • ?count(conditions, callback)
  • ?create(doc, callback)
  • ? update(conditions, doc, options, callback)
  • ? etc

Document document object

  • ? When querying the database through the Model, a Document object or an array of Document objects will be returned.
  • ? Document inherits from Model and represents a collection of documents.
  • ? Document objects can also interact with the database.

Methods of the Document object

  • ?equals(doc)
  • ?id
  • ?get(path,[type])
  • ?set(path,value,[type])
  • ?update(update,[options],[callback])
  • ?save([callback])
  • ? remove([callback])
  • ?isNew
  • ?isInit(path)
  • ?toJSON()
  • ?toObject()