Mongodb learning notes 2 Mongoose
Introduction to Mongoose
- We all passed before
shell
To complete various operations on the database. Most of the time in development, we need to complete the operation on the database through programs
- and
Mongoose
It 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 database
Collection
- 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 first
mongoose
package
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()
shell
To complete various operations on the database. Most of the time in development, we need to complete the operation on the database through programsMongoose
It is a module that allows us to operate mongodb through node(ODM)
Library, which further optimizes and encapsulates the node’s native mongodb module and provides more common functions(Schema)
-Restraint- The schema object definition constrains the document structure in the database
- As the representation of all documents in the collection, the model object is equivalent to the collection in the mongodb database
Collection
- Document represents a specific document in the collection, which is equivalent to a specific document in the collection
mongoose
package
npm install mongoose
const mongoose = require("mongoose");
mongoose. Connect ("mongodb: // address")
- Address example:
mongodb://127.0.0.1/test
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 underlying
Connection
Objects can be passed throughmongoose
Modularconnection
Property to access connection
Object is a connection to a databaseabstract
, it provides object connection, underlyingDb
Object and the model object that represents the combination- And you can be right
connection
Object to learn about the beginning and disconnection of the database connection - For example, yes
open
andclose
Event 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
- use
Mongoose
You 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
ObjectId
orOid
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 pass
mongoose
ofSchema
Property, which is a constructornew Schema(definition,option)
definition
: description modeoptions
: 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 truecapped
-Maximum number of documents in the collectioncollection
-Specify applicationSchema
Set name forid
-Boolean value, whether it is applied to_id
Processor ID, defaulttrue
_id
-Boolean value, whether to assign automaticallyid
Field, defaulttrue
strict
-Boolean, inconsistentSchema
The 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 definedModel
Model object
5. Model object
- To create a model object, you need to use
mongoose
ofmodel()
The syntax is as follows:model(name.[schema],[collection],[skipInit])
name:
Equivalent to the name of the model, which can be passed in the futurename
Find modelschema
: create the model object to applycollection
: is the name of the collection to connect toskipInit
: whether to skip initialization. The default is yesfalse
- Once you put one
Schema
Object into aModel
Object, 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