This article is a learning record. Do not update with the official website!

For more information, visit the Official Mongoose documentation

Related articles MongoDB basic operation set

First, Mongoose introduction

  • Mongoose is an object model tool for convenient operation of mongodb in nodeJs asynchronous environment.
  • Mongoose is the NodeJS driver and cannot be used as a driver for other languages.
  • MongooseThere are two characteristics
    • 1, through the thought of relational database to design non-relational database
    • 2. Based on mongodb driver, simplify operation

Two, the installation and use of Mongoose

1. Install

npm i mongoose --save
Copy the code

2. Introduce Mongoose and connect to the database

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test'); If you have an account password, use the following connection method: Mongoose.connect ('mongodb://eggadmin:123456@localhost:27017/eggcms'); 
Copy the code

3. Define the Schema

Schema in a database is a collection of database objects. Schema is a kind of data schema used in Mongoose. It can be understood as the definition of table structure. Each schema maps to a collection in mongodb, which does not have the ability to manipulate databases

var UserSchema=mongoose.Schema({ name: String.age:Number.status:'number' })
Copy the code

4. Create the data model

With the Schema defined, the next step is to generate the Model. A model is a model generated by a Schema that performs operations on a database.

Note:

  • mongoose.modelYou can pass in two arguments or you can pass in three arguments
  • mongoose.model(Parameter 1: model name (uppercase), parameter 2:Schema)
  • mongoose.model(Parameter 1: model name (uppercase), parameter 2:Schema, parameter 3: database set name)
  • If passed two parameters, the model will connect to a complex database with the same model name: if the model is created using the following method, the model will operate on the Users collection.
var UserModel=mongoose.model('User', UserSchema); 
Copy the code
  • If three arguments are passed: the name of the collection defined by the third argument of the model default operation
var UserModel=mongoose.model('User', UserSchema, 'users'); 
Copy the code

5. Find data

UserModel.find({}, function(err, docs) {
  if (err) {
    console.log(err);
    return;
  }
  console.log(docs);
});
Copy the code

6. Add data

// Instantiate the model to pass in the added data
var u = new UserModel({
  name: "lisi2222".age: 20.status: true
});
u.save();
Copy the code

7. Modify data

UserModel.updateOne({ name: "lisi2222" }, { name: "Ha ha ha." }, function(err, res) {
  if (err) {
    console.log(err);
    return;
  }
  console.log("Success");
});
Copy the code

8. Delete data

UserModel.deleteOne({ _id: "5b72ada84e284f0acc8d318a" }, function(err) {
  if (err) {
    console.log(err);
    return;
  } 
  // Only one will be deleted
  console.log("Success");
});
Copy the code

9. Search after the save is successful

var u = new UserModel({
  name: "lisi2222333".age: 20.status: true // Type conversion
});
u.save(function(err, docs) {
  if (err) {
    console.log(err);
    return;
  } 
  //console.log(docs);
  UserModel.find({}, function(err, docs) {
    if (err) {
      console.log(err);
      return;
    }
    console.log(docs);
  });
});
Copy the code

Three, Mongoose modular

Since all database operations are based on schema generated models, to avoid the trouble of generating models everywhere, encapsulate them and import them wherever they are used.

1, encapsulation

The project directory creates the Models directory

/* Models /db.js connect to the database */

var mongoose = require("mongoose");
// The useNewUrlParser attribute identifies the DB required by the user in the URL. It is not required to be specified before the upgrade and must be specified after the upgrade.
mongoose.connect(
  "mongodb://usersDB_readwrite:123456@localhost:27017/newsDB",
  { useNewUrlParser: true.useUnifiedTopology: true },
  function (err) {
    if (err) {
      console.log(err);
      return;
    }
    console.log("Database connection successful"); });module.exports = mongoose;

Copy the code
/* models/ usermodel.js
var mongoose = require("./db.js");
var UserSchema = mongoose.Schema(
  {
    account: { type: String.trim: true }, / / account
    password: { type: String.trim: true }, / / password
    username: { type: String.trim: true }, / / name
    email: String./ / email
    avatar: String./ / avatar
    profile: String./ / profile
  },
  { versionKey: false});var userModel = mongoose.model("User", UserSchema, "users");
module.exports = userModel;
Copy the code

2, use,

/* routes/user.js used here for Express, same as other frameworks. 2. Call */

var express = require("express");
/ / introduce userModel
var UserModel = require(".. /models/userModel");
var Result = require(".. /common/Result");
var router = express.Router();

// Register the interface
router.post("/regist".function (req, res, next) {
  // Instantiate the model with the received registration parameters
  let newUser = new UserModel(req.body);
  // Call save to save
  newUser.save(function (err) {
    if (err) {
      console.log(err);
      return;
    }
    res.json(200.new Result({ msg: "New user saved successfully" }));
  });
});
Copy the code

4, Mongoose modifier

1. Predefined schema modifiers

Mongoose provides predefined schema modifiers to do some formatting with our added data.

var UserSchema = mongoose.Schema({
  name: { type: String.trim: true },
  age: Number.status: { type: Number.default: 1}});Copy the code
  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array
  • Decimal128

Detailed introduction

1. Customizing modifiers (get & Set)

In addition to mongoose’s built-in modifiers, we can format data as we add it using the set (recommended) modifier. You can also use GET (not recommended) to format the data while the instance is fetching it.

// Demo
var NewsSchema = mongoose.Schema({
  title: "string".author: String.pic: String.redirect: {
    type: String.set: function(url) {
      if(! url)return url;
      // Prefix completion at write time (changes data)
      if (url.indexOf("http://") != 0 && url.indexOf("https://") != 0) {
        url = "http://" + url;
      }
      return url;
    },
    get: function(url) {
      if(! url)return url;
      // Prefix completion while reading (does not change data)
      if (url.indexOf("http://") != 0 && url.indexOf("https://") != 0) {
        url = "http://" + url;
      }
      returnurl; }},content: String.status: { type: Number.default: 1}});Copy the code

5. Mongoose Index

An index is a structure that sorts the values of one or more columns of a database table, making it faster to query the database. MongoDB indexes are almost identical to traditional relational databases, including some basic query optimization techniques.

var DeviceSchema = new mongoose.Schema({
  sn: {
    type: Number.// Unique index
    unique: true
  },
  name: {
    type: String.// Plain index
    index: true}});Copy the code

Six, Mongoose CURD

1. Built-in CURD

  • Model.deleteMany()
  • Model.deleteOne()
  • Model.find()
  • Model.findById()
  • Model.findByIdAndDelete()
  • Model.findByIdAndRemove()
  • Model.findByIdAndUpdate()
  • Model.findOne()
  • Model.findOneAndDelete()
  • Model.findOneAndRemove()
  • Model.findOneAndUpdate()
  • Model.replaceOne()
  • Model.updateMany()
  • Model.updateOne()

2. Expand CURD

var UserSchema=mongoose.Schema({
    name: {type:String       
    },
    sn: {type:String.index:true
    },
    age:Number.status: {type:Number.default:1}})// Static method
UserSchema.statics.findBySn=function(sn,callback){
    // Use the find method to retrieve sn data
    this.find({"sn":sn},function(err,docs){
        callback(err,docs)
    })   
}

// Instance methods (mostly unused)
UserSchema.methods.print=function(){
    console.log('I'm an instance method')
    console.log(this.name)
}
Copy the code
// Custom static methods
UserModel.findBySn('123456782'.function(err,docs){
    if(err){
        console.log(err);
        return;
    }
    console.log(docs)
})

var user = new UserModel({
    name: 'Daisy'.sn:'123456781'.age: 29
});
// Custom instance methods
user.print();
Copy the code

7, multiple table associated query

1, the aggregate

MongoDB Aggregate aggregate pipeline

var mongoose = require("./db.js");
var OrderSchema = mongoose.Schema({
  order_id: String.uid: Number.trade_no: String.all_price: Number.all_num: Number
});
var OrderModel = mongoose.model("Order", OrderSchema, "order");
OrderModel.aggregate(
  [
    {
      $lookup: {
        from: "order_item".localField: "order_id".foreignField: "order_id".as: "item"}}].function(err, docs) {
    // The order table associates order_ITM with the order_ITM table, assigning order_item's data to item and returning it
    console.log(docs); });Copy the code

Associated query of three tables

 ArticleModel.aggregate([
  {

    $lookup: {
      from: "articlecate".localField: "cid".foreignField: "_id".as: "cate"}}, {$lookup: {
      from: "user".localField: "author_id".foreignField: "_id".as: "user"}}].function(err,docs){

  console.log(JSON.stringify(docs));
})
Copy the code

2. Populate associated queries

var mongoose=require('./db.js');
var ArticleSchema = mongoose.Schema({
    title: {type: String.unique: true     
    },
    cid : { 
        type: Schema.Types.ObjectId,   
        ref:"ArticleCate"    // CID establishes a relationship with article categories. (model name)
    },   Classification / * * / id
    author_id: {type: Schema.Types.ObjectId ,
        ref:"User"    Author_id establishes a relationship with the user table. (model name)
    },   /* User id*/
    author_name: {type:String      
    },
    descripton:String.content   : String
});

module.exports=mongoose.model('Article',ArticleSchema,'article');
Copy the code
// Note that populate needs to import the model used
var ArticleCateModel=require('./model/articlecate.js');
var ArticleModel=require('./model/article.js');
var UserModel=require('./model/user.js');

// The association between the articles table and the categories table
ArticleModel.find({}).populate('cid').exec(function(err,docs){
	console.log(docs);
})

// Three tables are associated
ArticleModel.find({}).populate('cid').populate('author_id').exec(function(err,docs){
	console.log(docs);
})

Copy the code

It is recommended to use Aggregate.