Mongoose profile

Mongoose website: mongoosejs.com/

Why Mongoose

Mongoose is a module that allows you to operate MongoDB via Node. Mongoose is essentially an object document Model (ODM) library that encapsulates Node’s native MongoDB module and provides more functionality.

The advantage of the Mongoose

  1. Databases can be manipulated as objects
  2. You can create a Schema structure for your document
  3. Documents/documents in the model can be validated
  4. Data can be typed into an object model
  5. Middleware can be used to apply business logic hooks
  6. Easier than Node’s native MongoDB driver

Use the Mongoose

  1. CNPM install Mongoose –save

  2. Quote mongoose: var mongoose =require(“mongoose”);

  3. Connect to db: var db =mongoose. Connect (“mongodb://user:pass@localhost:port/database”)

  4. Run the following code to check whether the default database test can be connected successfully.

var mongoose =require("mongoose");
var db =mongoose.connect("mongodb://localhost/m_data");
db.connection.on("error".function (error) {
   console.log("Database connection failed:" + error);
});
db.connection.on("open".function () {
   console.log("Database connection successful!");
});
db.connection.once('close', ()=>{
    console.log('Connection has been disconnected! ')})Copy the code

Mongoose basic use

A few new targets for Mongoose

In MongoDB, multiple documents can form collections (hereinafter referred to as collections), and multiple collections can form databases. If you want to manipulate MongoDB data, you need to have a “document” that contains the data mentioned above.

  1. Documents – the core concept of MongoDB is an ordered set of key-value pairs. Documents are represented as objects in JavaScript. It is also the basic unit of data in MongoDB, much like rows in a relational DATABASE management system, but more expressive.
  2. Collection – Consists of a set of documents. If you compare a document in MongoDB to a row in a relational database, a collection is equivalent to a table.
  3. Schema — a database model skeleton stored in the form of files. It does not directly lead to the database, that is, it does not have the ability to operate on the database. It only defines the types of data, so to speak, it is a data attribute model (traditional sense of table structure), or a “collection” model skeleton. Everything in Mongoose started with Schema. Each Schema corresponds to a collection in MongoDB. Schema defines the style of documents in the collection.

Define a Schema (table/Schema object)

// Create a new Schema to define rules/field rulesletSchema= mongoose.Schema; The fields (rules) defining the personSchema need to be new, sort of like constructorslet personSchema= new Schema({
    name: String,
    sex: String,
    age: Number
});
Copy the code

The basic attribute types are:

  • String
  • Number
  • Date
  • Boolean
  • Buffer
  • ObjectId
  • Mixed
  • Array

Model — A Model generated by a Schema construct that manipulates specific data that conforms to the Schema’s data type rules.

Create a Model (Collection)

let personModel= mongoose.model('person', personSchema);
Copy the code

Person: The name of the collection in the database to which we add data if the Person already exists, it will be saved to its directory, if not, the Person collection will be created and the data will be saved.

//4. Insert the document personModel.create({name:'Zhang Ning Le',
    sex: 'male',
    age: 18
}, (err)=>{
   if(! err){ console.log('Insert successful! ')}else{ throw err; }});Copy the code

Mongoose insert and query

Mongoose lookup data of some methods: mongoosejs.com/docs/api.ht…

Insert multiple data

personModel.create([
    {name:'Zhang Baodou',age: 2,sex: 'male'},
    {name:'Cow Hee Hee',age: 2,sex: 'woman'}
], (err)=>{
   if(! err){ console.log('Insert successful! ')}else{ throw err; }})Copy the code

The query

  • Model.find()
personModel.find({name: 'Zhang Ning Le'}, (err, data)=>{
    if(! err){ console.log(data) }else{ throw err; }})Copy the code

Query all

  • Model.find({}, callback)
personModel.find({}, (err, data)=>{
    if(! err){ console.log(data) }else{ throw err; }})Copy the code

You can also select the criteria for finding data (0 hides and 1 shows the ID by default) in the same way that MongoDB uses it on the command line

/ / query is only show the name personModel. Find ({}, {name: 1, _id: 0}, (err, data) = > {if(! err){ console.log(data) }else{ throw err; }})Copy the code

Skip (the start of the query) and limit (the number of items added) are also used in find()

personModel.find({}, {name: 1, _id: 0, age: 1}, {skip: 0, limit: 2}, (err, data)=>{// Only name and age are displayedif(! err){ console.log(data) }else{ throw err; }})Copy the code

Directing the find () and findOne () command can be used in the mongoose specific reference: mongoosejs.com/docs/api.ht…

Mongoose modify and delete

Reference: mongoosejs.com/docs/api.ht…

Modification method:

  • Model.update()
  • Model.updateMany()
  • Model.updateOne()
  • Model.watch()
personModel.update({name: 'Zhang Ning Le'}, {$set: {age: 20}}, (err, data)=>{
   if(! err){ console.log('Modified successfully! ')
       console.log(data)
   }else{ throw err; }})Copy the code

Delete methods

  • Model.remove()
  • Model.deleteMany()
  • Model.deleteOne()
personModel.remove({name:'Cow Hee Hee'}, (err)=>{
    if(! err){ console.log('Deleted successfully! ')}else{ throw err; }})Copy the code

Statistics the number of documents

  • Model.count()
personModel.count({}, (err,count)=>{
    if(! err){ console.log('Query succeeded! A total of: ' + count + '条');
    }else{ throw err; }})Copy the code

Entity

Entity — An Entity created by Model that uses the save method to save data. The actions of both Model and Entity can affect the actions of the database, but Model is more manipulative than Entity. Create Entity using Model as shown in the following example:

let mongoose= require('mongoose');
let db= mongoose.connection('mongodb://localhost/m_data');
db.on('open', ()=>{
    console.log('Connection successful! ')})let Schema= mongoose.Schema;
let personSchema= new Schema({
    name: String,
    sex: String,
    age: Number
});
let personModel= mongoose.model('person', personSchema);
let personEntity = new personModel({
    name: 'xu wei',
    sex: 'male',
    age: 38
})
personEntity.save((err, person)=>{
    if(! err){ console.log('Saved successfully! ')
        console.log(person);
    }else{
        console.log('Save failed! ')}})Copy the code

Reference: blog.csdn.net/swimming_in…