1. Mongoose module
(1) It is an object model tool that encapsulates the operation of MongoDB database under the environment, and can convert the data in the MongoDB database into JavaScript objects for users to use.
(2) Noun:
- Schema: It is a database model skeleton stored in file form. It does not have the ability to operate databases. It is just a manifestation of the database in program fragments and can be understood as a table structure.
- Model: Model generated by Schema release, database operations with abstract properties and behaviors
- Entity: An entity created by a Model, its operations will also affect the database
(3) Naming specification: Camel naming Example:
PersonSchema: Person corresponding Schema, Person's text attributes (table structure)
PersonModel: Model corresponding to Person
PersonEntity: Person corresponding Entity
Schema generates Model, and Entity is generated from Model. Model and Entity can operate the database, and Model is more operable.
2. Use of Mongoose module
(1) Installation: npm install mongoose
(2) Create a database connection file
// Import mongoose moduleconst Mongoose = require('mongoose'); // Define the connection string of the MongoDB database: Protocol://host address: port number/database nameconst mdb_url = 'mongodb://localhost:27017/my_test'; /* Establish a connection to MongoDB database useNewUrlParser: Whether to use the new URL address conversion method useUnifiedTopology: Whether to use new user security policies */ (mdb_url,{useNewUrlParser:true,useUnifiedTopology:true}); // Process the connection process// Establish a connection - the connection successfully triggers the connected event('connected',()=>{ ('The database connection is successful ~'+mdb_url); }) // Connection exception - Exception information is saved in the parameters of the callback function('error',(e)=>{ (e); }) //Disconnection - Disconnection contact('disconnected',()=>{ ('Disconnect the database ~'); }) // Export mongoose = Mongoose;
(3) Create Schema, and then create Model with Schema
- Schema: Defines the skeleton corresponding to the set. The properties in Schema correspond to the key of the collection in MongoDB.
- is an instance of Schema that is used to manipulate documents in collections in MongoDB.
3. Regarding the correspondence between model name and collection name in the database
(1) There is no collection in the database
('Admin',AdminSchema) —> Add s after the model name is the collection name (case insensitive) — admins
('Admin',AdminSchema,'admin') -->The third parameter is the collection name used to define
(2) There are collections in the database
('Admin',AdminSchema,'The existing collection name in the database')
4. Basic operations of mongoose
(1) Insert the document: save method
- Create Entity using Model
- Then use Entity to call the save method
const AdminModel = require('../model/adminModel'); // Create an object through modelconst admin = new AdminModel({ _id:'1005', userName:'Tang Monk', password:'123456', address:'Dongtu Datang' }) /* * Call the save method through the object to insert data into the database. Err stores information after the storage failed. Res is the saved object. */ ((err,res)=>{ if(err){ (err); }else{ (res); } })
(2) Delete the document: findByIdAndDelete: It is called directly through the Model, and the function is to delete it according to the document's _id attribute
(3) Delete document: deleteOne: Directly call through Model, delete document according to the given conditions
(4) Update the document: findOneAndUpdate, call directly through Model
findOneAndUpdate(condition, update statement, {}, callback function)
( {'_id':'1004'}, //Denote the query conditions {$set:{'password':'789567'}}, //Update statement null, // means query operation, usually null (err,data)=>{ //Update the callback function, err represents the error message of the database, and the document queryed by findOne stored in data is stored in findOne if(err){ (err); //err indicates database error: an exception occurred during query and update of the database. }else if(!data){ // When data is null, no corresponding document was found ('Update failed~'); }else if(data){ // When data is not null, it means that the corresponding document is found ('Update successfully ~') } })
(5) Update document: updateOne (condition, update statement, callback function)
({'password':'123456'},{$set:{'password':'567890'}},(err,data)=>{ if(err){ (err); } (); })
(6) Query all: find
((err,data)=>{ if(err){ (err); } (data); })
(7) Press _id to query: findById
({ '_id':'1004' },(err,data)=>{ if(err){ (err); } (data); })
(8) Multi-condition query: findOne returns the first record that meets the condition
({ address:'Three Kingdoms', password:'123456' },(err,data)=>{ if(err){ (err); } (data) })
(9) Number of documents in the query collection: count
((err,data)=>{ if(err){ (err); } ('Records:'+data); })
This is the article about the implementation method of the NodeJs Express framework for operating MongoDB databases. For more information about the NodeJs Express framework, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!