Mongodb learning notes II – Mongoose

Time:2021-12-30

Mongodb learning notes 2 Mongoose

Introduction to Mongoose

  • We all passed beforeshellTo complete various operations on the database. Most of the time in development, we need to complete the operation on the database through programs
  • andMongooseIt 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 node’s native mongodb module and provides more common functions
  • In most cases, it is used to apply structured patterns to a mongodb collection and provides benefits such as validation and type conversion

Benefits of Mongoose

  • You can create a schema structure for a document(Schema)-Restraint
  • You can validate objects / documents in the model
  • Data can be converted to an object model by type conversion
  • Middleware can be used to apply business logic hooks
  • It is easier than the node’s native mongodb driver

New object

  • Mongoose provides us with several new objects
    • The schema object definition constrains the document structure in the database
  • Model
    • As the representation of all documents in the collection, the model object is equivalent to the collection in the mongodb databaseCollection
  • Document
    • Document represents a specific document in the collection, which is equivalent to a specific document in the collection

1. Connect mongodb through Mongoose

  • Mongoose must be installed firstmongoosepackage
    • npm install mongoose
  • Load Mongoose
    • const mongoose = require("mongoose");
  • Connect to database
    • mongoose. Connect ("mongodb: // address")
    • Address example:mongodb://127.0.0.1/test
  • Disconnect
    • mongoose.disconnect()

**Note * *: if the port number is the default port number (27017), it can be omitted


2. Listen to the connection status of mongodb database – connection

connection

  • Once the mongodb database is connected, the underlyingConnectionObjects can be passed throughmongooseModularconnectionProperty to access
  • connectionObject is a connection to a databaseabstract, it provides object connection, underlyingDbObject and the model object that represents the combination
  • And you can be rightconnectionObject to learn about the beginning and disconnection of the database connection
  • For example, yesopenandcloseEvent to monitor the opening and closing of the connection

These are official nonsense, in short ⬇:

  • In the mongoose object, there is a property called connection, which represents the database connection
    • By monitoring the status of the object, you can monitor the connection and disconnection of the database

Event of successful database connection
mongoose.connection.once("open",function(){});

Event of database connection disconnection (generally no need to call)
mongoose.connection.once("close",function(){});

3. helloMongose

// 01- helloMongose.js
//Introduce mongoose module
const mongoose = require("mongoose");

//Connect to database
mongoose.connect("mongodb://localhost:27017/test");

//Test whether the connection is successful
mongoose.connection.once("open", function () {
    //Connection successfully executed
    console. Log ('connection succeeded ~ ';
});

After execution, you can see that you have successfully connected to the database
在这里插入图片描述
But note: in the screenshot above, we can see a line of error prompt:
在这里插入图片描述
Translated as

  • The current URL string parser is deprecated and will be removed in future releases. To use the new parser, pass the option {usenewurlparser: true} to mongoclient connect。
  • This error will not affect the operation of the program, but according to the specification, we change the code to the following
  • mongoose.connect("mongodb://localhost:27017/test",{useNewUrlParser: true ,useUnifiedTopology: true});

4. Create schema object

  • useMongooseYou must always define patterns
  • The schema defines fields and field types for documents in the collection
  • This is useful if your data is structured to support patterns
  • In short, a pattern is a constraint on the document. With a pattern, the fields in the document must comply with the provisions of the pattern, otherwise they will not operate normally

4.1 definition mode

  • The schema defines fields and field types for documents in the collection
  • For each field in the pattern, you need to define a specific value type. The supported types are as follows:
    • String
    • Number
    • Boolean
    • Array
    • Buffer
    • Date
    • ObjectIdorOid
    • Mixed
  • You need to define a schema for each different document type you plan to use

4.2 creating a schema definition

  • Mode needs to passmongooseofSchemaProperty, which is a constructor
    • new Schema(definition,option)
      • definition: description mode
      • options: configure objects to define the interaction of collections in the database

4.3 options common options

  • autoIndex
    -Boolean, turn on automatic indexing, defaulttrue
  • bufferCommands
    -Boolean value to cache statements that cannot be executed due to connection problems. The default value is true
  • capped
    -Maximum number of documents in the collection
  • collection
    -Specify applicationSchemaSet name for
  • id
    -Boolean value, whether it is applied to_idProcessor ID, defaulttrue
  • _id
    -Boolean value, whether to assign automaticallyidField, defaulttrue
  • strict
    -Boolean, inconsistentSchemaThe object will not be inserted into the database by defaulttrue

4.4 code

code ⬇:

const mongoose = require("mongoose");

//Connect to database
mongoose.connect("mongodb://localhost:27017/test",{useNewUrlParser: true ,useUnifiedTopology: true});

//Test whether the connection is successful
mongoose.connection.once("open", function () {
    //Connection successfully executed
    console. Log ('connection succeeded ~ ';
});

//Create a schema object and assign it to a variable
const Schema = mongoose.Schema;

//Create a schema object
const stuSchema = new Schema({
    name: String,
    age: Number,
    gender: {
        type:String,
        Default: 'male'
    },
    address:String
});

At this time, the data cannot be inserted into the database, and it needs to be definedModelModel object


5. Model object

  • To create a model object, you need to usemongooseofmodel()The syntax is as follows:
    • model(name.[schema],[collection],[skipInit])
      • name: Equivalent to the name of the model, which can be passed in the futurenameFind model
      • schema: create the model object to apply
      • collection: is the name of the collection to connect to
      • skipInit: whether to skip initialization. The default is yesfalse
  • Once you put oneSchemaObject into aModelObject, you are fully ready to start accessing, adding, deleting, updating and deleting documents in the model. In other words, with the model, we can operate the database

5.1 implementation code

//Introduce mongoose module
const mongoose = require("mongoose");

//Connect to database
mongoose.connect("mongodb://localhost:27017/test",{useNewUrlParser: true ,useUnifiedTopology: true});

//Test whether the connection is successful
mongoose.connection.once("open", function () {
    //Connection successfully executed
    console. Log ('connection succeeded ~ ';
});

//Create a schema object and assign it to a variable
const Schema = mongoose.Schema;

//Create a schema object
const stuSchema = new Schema({
    name: String,
    age: Number,
    gender: {
        type:String,
        Default: 'male'
    },
    address:String
});

//Create model through scheme
//Model represents the collection in the database. Only through model can the database be operated
// mongoose.model(modelName,schema);
//Modelname: is the name of the set to be mapped. Mongoose will automatically change the set name to a plural
//Schema: created schema object


const stuModel = mongoose.model('student', stuSchema);

//Insert a document into the database
// stuModel.create(doc,function(err){})
stuModel.create({
    Name: 'Xiao Ming',
    age: 18,
    Gender: 'male',
    Address: 'Shanghai'
}, function (err) {
    if (!err) {
        console. Log ('Insert succeeded ');
    }
})

Operation results:
在这里插入图片描述

After clicking the database, you can find that the data has been inserted successfully
在这里插入图片描述