[Nodejs] Operate mongodb database

insert image description here

1 Introduction


  • Mongoose is a module that allows us to operate MongoDB through Node.
  • Mongoose is an object document model (ODM) library, which further optimizes and encapsulates Node's native MongoDB module and provides more functions. In most cases, it is used to apply structured schemas to a MongoDB collection, and provides benefits such as validation and type conversion
  • Objects in mongoose:
    • Schema mode object (Schema object definition constrains the document structure in the database)
    • Model model object (Model object is used as a representation of all documents in the collection, which is equivalent to the collection collection in the MongoDB database)
    • Document document object (Document represents a specific document in the collection, which is equivalent to a specific document in the collection)

The benefits of mongoose

  • A schema structure (Schema) can be created for the document
  • Validation can be done on objects/documents in the model
  • Data can be converted to an object model by typecasting
  • Middleware can be used to apply business logic hooks
  • Easier than Node's native MongoDB driver

Install

npm i -S mongoose

2. Connect to the database


config/db.config.js

// 1.引入mongoose
const mongoose = require("mongoose");

// 2.连接mongodb数据库
// 指定连接数据库后不需要存在,当你插入第一条数据库后会自动创建数据库
/*
mongoose.connect('mongodb://数据库地址:端口号/数据库名',{useMongoClient:true})
如果端口号是默认端口号(27017)则可以省略不写
*/
mongoose.connect('mongodb://127.0.0.1:27017/ds2', {
    
    
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
})

// 3.监听mongodb数据库的连接状态
// 绑定数据库连接成功事件
mongoose.connection.once("open", function () {
    
    
    console.log("连接成功");
});
// 绑定数据库连接失败事件
mongoose.connection.once("close", function () {
    
    
    console.log("数据库连接已经断开");
});

// 4.断开数据库连接(一般不用)
mongooes.disconnect();

Note: MongoDB database, under normal circumstances, only needs to be connected once. After connecting once, unless the project stops and the server is closed, the connection will generally not be disconnected

Use direct require(".../config/db.config.js") in the www file in the bin directory to start the database connection
insert image description here

3. Create schema objects and model objects


The Schema in the database is a collection of database objects. Schema is a data mode used in mongoose, which can be understood as the definition of table structure; each schema will be mapped to a collection in mongodb, which does not have the ability to operate the database.

  • Each schema is mapped to a MongoDB collection and defines the document structure in this collection
  • Supported field types
type effect
String define string
Number define numbers
Date define date
Buffer define binary
Boolean define boolean value
Mixed Define a hybrid type
ObjectId define object id
Array define array

model/UserModel.js

const mongoose = require("mongoose")
const Schema=mongooes.Schema;
//创建模式对象
const UserType=new Schema({
    
    
    name:{
    
    
           type: 'string',
           //添加约束,保证数据的完整性,让数据按规矩统一
           require: true
        },
    age:Number,
    gender:{
    
    
        type:String,
        // 默认值
        default:'female'
    },
    address:String
})

//创建模型对象
//通过Schema来创建Model
//Model代表的是数据库中的集合,通过Model才能对数据库进行操作
//mongoose.model(modelName,schema)
//建立映射关系,students是集合,mongoose会自动将集合变成复数比如student会变成students
//大写也会被自动转换为小写,比如Users会变成users
const UserModel=mongoose.model("UserModel",UserType,"user"); 
//第一个参数表示创建的集合的名称,第二个参数表示利用的模式对象,第三个参数是强行指定集合名称

module.exports  = UserModel 

4. Documentation added


4.1 save()

The operation is the document
case:

var mongoose = require('mongoose')
const UserModel = require('../model/UserModel');

//链式调用 通过new 一个Model创建一个 document
new UserModel({
    
    name:"小明",age:18}).save((err,docs) => {
    
    
    if(!err){
    
    
        console.log(docs)
        res.send({
    
    
          code: 200,
          data: {
    
    
            id: docs._id,
          },
        })
        //{ _id: 6017bd1cf4cc8544d8ed2a8a, name: '小明', age: 18, __v: 0 }
    }
})   

4.2 create()

  • operating model
  • Model.create(doc(s), [callback])
  • Parameters:
    [doc(s)]: document object or array of document objects
    [callback]: callback function
var mongoose = require('mongoose')
const UserModel = require('../model/UserModel');

UserModel.create({
    
    name:"小明",age:18},{
    
    name:"小红",age:10},(err,doc1,doc2) => {
    
    
   if(!err){
    
    
        console.log(doc1)
        //{ _id: 6017be2d77c8dd01242624bb, name: '小明', age: 18, __v: 0 }
        console.log(doc2)
        //{ _id: 6017be2d77c8dd01242624bc, name: '小红', age: 10, __v: 0 }
    }
})

other:

//Model.createOne(doc, [callback]);		创建一个对象
//Model.createMany(doc, [callback]);		创建多个对象
//	-doc是需要插入的文档
//	-callback(err) 是回调函数,可以用来提示是否创建成功了
4.3 insertMany()
Model.insertMany(doc(s), [options], [callback])
返回值为一个数组
案例:
UserModel.insertMany({
    
    name:"小明",age:18},{
    
    name:"小芳",age:14},(err,docs) => {
    
    
   if(!err){
    
    
        console.log(docs)
        /*[{ _id: 6017befb5c36d64d08b72576, name: '小明', grades: 68, __v: 0 },
           { _id: 6017befb5c36d64d08b72577, name: '小芳', grades: 94, __v: 0 }]*/
    }
})

5. Document query


_id name grades __v
6017befb5c36d64d08b72576 Xiao Ming 68 0
6017befb5c36d64d08b72577 Xiaofang 94 0
6017c455ba09d355a49ec8eb little red 52 0
6017c455ba09d355a49ec8ec Xiao Gang 46 0

5.1 find()

  • Model.find(conditions, [projection], [options], [callback])

  • parameter

    • ​ conditions: query conditions
    • ​ [projection]: control return field
    • ​ [options]: configure query parameters
    • ​ [callback]: callback function – function(err,docs){}
  • case:

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',(err) => {
    
    
    if(!err){
    
    
        var schema = new mongoose.Schema({
    
    name:String,grades:Number})
        var stuModel = mongoose.model('grades',schema)
        //查询所有数据
        stuModel.find((err,docs) => {
    
    
           if(!err){
    
    
            	console.log(docs)
        	}
        })        
       /* [{ _id: 6017befb5c36d64d08b72576, name: '小明', grades: 68, __v: 0 },
           { _id: 6017befb5c36d64d08b72577, name: '小芳', grades: 94, __v: 0 },
           { _id: 6017c455ba09d355a49ec8eb, name: '小红', grades: 52, __v: 0 },
           { _id: 6017c455ba09d355a49ec8ec, name: '小刚', grades: 46, __v: 0 }]*/
        
        //查询成绩大于60以上的数据
        stuModel.find({
    
    grades:{
    
    $gte:60}},(err,docs) => {
    
    
            if(!err){
    
    
                 console.log(docs)
             }
         })
        /*[{ _id: 6017befb5c36d64d08b72576, name: '小明', grades: 68, __v: 0 },
           { _id: 6017befb5c36d64d08b72577, name: '小芳', grades: 94, __v: 0 }]*/
        
        //查询成绩大于60以上且名字里存在‘芳’的数据
        stuModel.find({
    
    name://,grades:{
    
    $gte:60}},(err,docs) => {
    
    
            if(!err){
    
    
                 console.log(docs)
             }
         })
        /*[
        *     { _id: 6017befb5c36d64d08b72577, name: '小芳', grades: 94, __v: 0 }
        * ]*/
        
        //查询名字里存在‘明’的数据且只输出‘name’字段
        //_id默认会返回
        stuModel.find({
    
    name://},{
    
    name:1,_id:0},(err,docs) => {
    
    
            if(!err){
    
    
                 console.log(docs)
             }
         })
        // [{name: '小明'}]
        
        //跳过前两条数据并限制只输出一条数据
        stuModel.find(null,null,{
    
    skip:2,limit: 1},(err,docs) => {
    
    
            if(!err){
    
    
                 console.log(docs)
             }
         })
        /*[{ _id: 6017c455ba09d355a49ec8eb, name: '小红', grades: 52, __v: 0 }*/
    }
})

5.2 findById()

  • Model.findById(id, [projection], [options], [callback])
  • case:
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',(err) => {
    
    
    if(!err){
    
    
        var schema = new mongoose.Schema({
    
    name:String,grades:Number})
        var stuModel = mongoose.model('grades',schema)
        //保存查询数据的_id
        var aIDArr = []
        
        //查询所有数据
        stuModel.find((err,docs) => {
    
    
           if(!err){
    
    
            	docs.forEach((item,index,arr)=>{
    
    
                    aIDArr.push(item._id)
                })
                //显示第 0 个元素的所有字段
                stuModel.findById(aIDArr[0],(err,doc)=>{
    
    
                    if(!err){
    
    
                        console.log(doc)
                    }
                })
               // { _id: 6017befb5c36d64d08b72576, name: '小明', grades: 68, __v: 0 }
               
                //显示第 0 个元素且只输出name字段
                stuModel.findById(aIDArr[0],{
    
    name:1,_id:0},(err,doc)=>{
    
    
                    if(!err){
    
    
                        console.log(doc)
                    }
                })
               // { name: '小明' }
               
                //显示第 0 个元素且输出最少的字段(_id默认输出)
                stuModel.findById(aIDArr[0],{
    
    lean:true},(err,doc)=>{
    
    
                    if(!err){
    
    
                        console.log(doc)
                    }
                })
               // { _id: 6017befb5c36d64d08b72576 }
        	}
        })
    }
})

5.3 findOne()

  • Returns the first of the queried data
  • Model.findOne([conditions], [projection], [options], [callback])
  • case:
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',(err) => {
    
    
    if(!err){
    
    
        var schema = new mongoose.Schema({
    
    name:String,grades:Number})
        var stuModel = mongoose.model('grades',schema)
        //找出age>80的文档中的第一个文档
        stuModel.findOne({
    
    grades:{
    
    $gt:80}},(err,doc) => {
    
    
           if(!err){
    
    
            	console.log(doc)
        	}
        })
        //{ _id: 6017befb5c36d64d08b72577, name: '小芳', grades: 94, __v: 0 }

        //找出age>80的文档中的第一个文档,且只输出name字段
        stuModel.findOne({
    
    grades:{
    
    $gt:80}},{
    
    name:1,_id:0},(err,doc) => {
    
    
            if(!err){
    
    
                 console.log(doc)
             }
         })
         //{ name: '小芳' }

        //找出age>80的文档中的第一个文档,且输出包含name字段在内的最短字段
        stuModel.findOne({
    
    grades:{
    
    $gt:80}},{
    
    lern:true},(err,doc) => {
    
    
            if(!err){
    
    
                 console.log(doc)
             }
         })
         //{ _id: 6017befb5c36d64d08b72577 }
    }
})

5.4 Complex query【$where】

  • $where can use arbitrary JavaScript as part of the query, strings containing JavaScript expressions or functions
  • the case
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',(err) => {
    
    
    if(!err){
    
    
        var schema = new mongoose.Schema({
    
    name:String,grades:Number})
        //添加一个测试字段
        // schema.add({test:Number})
        var stuModel = mongoose.model('grades',schema)
        //添加两条数据
        // stuModel.create({name:"小花",grades:76,test:76},{name:"小兰",grades:60,test:30},(err,docs)=>{
    
    
        //     console.log(docs)
        // })

        //字符串 es5中this与obj指向一样,es6中只能用obj
        stuModel.find({
    
    $where:"this.grades == this.test" || "obj.grades == obj.test"},(err,doc) => {
    
    
           if(!err){
    
    
            	console.log(doc)
        	}
        })
        //[{_id: 6017d7cb8a95cb2a00aae3ae,name: '小花',grades: 76,test: 76,__v: 0}]

        //函数
        stuModel.find({
    
    $where:function() {
    
    
            return this.grades == this.test || obj.grades == obj.test*2
        }},(err,doc) => {
    
    
            if(!err){
    
    
                 console.log(doc)
             }
         })
         /*[{_id: 6017d7cb8a95cb2a00aae3ae,name: '小花',grades: 76,test: 76,__v: 0},
            {_id: 6017d7cb8a95cb2a00aae3af,name: '小兰',grades: 60,test: 30,__v: 0}]*/
    }
})

5.5 Common query conditions

$or     或关系

$nor    或关系取反

$gt     大于

$gte    大于等于

$lt     小于

$lte    小于等于

$ne     不等于

$in     在多个值范围内

$nin    不在多个值范围内

$all    匹配数组中多个值

$regex   正则,用于模糊查询

$size    匹配数组大小

$maxDistance  范围查询,距离(基于LBS)

$mod     取模运算

$near    邻域查询,查询附近的位置(基于LBS)

$exists   字段是否存在

$elemMatch  匹配内数组内的元素

$within    范围查询(基于LBS)

$box     范围查询,矩形范围(基于LBS)

$center    范围醒询,圆形范围(基于LBS)

$centerSphere 范围查询,球形范围(基于LBS)

$slice     查询字段集合中的元素(比如从第几个之后,第N到第M个元素

5.6 Specific Type Queries

_id name grades __v test
6017befb5c36d64d08b72576 Xiao Ming 68 0 1
6017befb5c36d64d08b72577 Xiaofang 94 0 3
6017c455ba09d355a49ec8eb little red 52 0 5
6017c455ba09d355a49ec8ec Xiao Gang 46 0 2
6017d7cb8a95cb2a00aae3ae little flower 76 0 4
6017d7cb8a95cb2a00aae3af Xiaolan 60 0 6

method

method effect
sort to sort
skip jump over
limit limit
select display field
exect implement
count count
distinct Deduplication

Both exec() and then()
return promise objects. exec is generally used for one-time execution of independent actions, and then is used for continuous actions. Their usage can also be distinguished from their method names. exec means execution , then is then how, the parameters of exec and then are different, the former is callback (err, doc), the latter is resolved (doc), rejected (err)

case:

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student')
var Schema =new mongoose.Schema({
    
     name:String,grades:Number,test:{
    
    type:Number,default:0}})
var stuModel = mongoose.model('grades', Schema);

// 按test从小到大排序
// 1是升序,-1是降序
stuModel.find().sort({
    
    test:1}).exec((err,docs)=>{
    
    
  console.log(docs)
})
// 按test从大到小排列
stuModel.find().sort('-test').exec((err,docs)=>{
    
    
  console.log(docs)
})
// 跳过1个,显示其他
stuModel.find().skip(1).exec((err,docs)=>{
    
    
  console.log(docs)
})
// 显示2个
stuModel.find().limit(2).exec((err,docs)=>{
    
    
  console.log(docs)
})
// 显示name、grades字段,不显示id字段
stuModel.find().select('name grades -id').exec((err,docs)=>{
    
    
  console.log(docs)
})
// 跳过第1个后,只显示2个数据,按照grades由大到小排序,且不显示id字段
stuModel.find().skip(1).limit(2).sort('-grades').select('-id').exec((err,docs)=>{
    
    
  console.log(docs)
  /[{
    
     name: '小明', grades: 78, v: 0, test: 1 },
     {
    
     name: '小花', grades: 76, test: 4, v: 0 }]/
})
// 显示集合stuModel中的文档数量
stuModel.find().count((err,count)=>{
    
    
  console.log(count)
  //6
})
// 返回集合stuModel中的grades的值
stuModel.find().distinct('grades',(err,distinct)=>{
    
    
  console.log(distinct)
  //[ 46, 52, 60, 76, 78, 94 ]
})

6. Document update


6.1 update()

  • Model.update(conditions, doc, [options], [callback])
  • parameter
    • conditions: query conditions
    • doc: data that needs to be modified (inserted data)
    • [options]: control options

safe (boolean): The default is true. safe mode. upsert (boolean): The default is false. Creates a new record if it does not exist. multi (boolean): The default is false. Whether to update multiple query records. runValidators: If the value is true, Validation validation is performed. setDefaultsOnInsert: If the upsert option is true, insert the default values ​​defined in the document when creating a new one. strict (boolean): update in strict mode. overwrite (boolean): Defaults to false. Disable update-only mode, allowing records to be overwritten.

  • [callback]: callback function
  • If the query condition is set, when the database is not satisfied, nothing will happen by default
  • The callback function in the update() method cannot be omitted, otherwise the data will not be updated. When the callback has no useful information, you can use exec() to simplify
stuModel.update({
    
    name:'小明'},{
    
    $set:{
    
    test:34}}.exec())

the case

//第一步,引入mongoose
const mongoose = require('mongoose')
//第二步,连接数据库
mongoose.connect('mongodb://localhost:27017/student',err=>{
    
    
  if(!err){
    
    
    //第三步,创建模板
    var Schema =new mongoose.Schema({
    
     name:String,grades:Number,test:{
    
    type:Number,default:0}})
    // var Schema = new Schema()
    //第四步,将模板映射到集合并创建
    var stuModel = mongoose.model('grades',Schema)

    //查询name为小明的数据,并将其test更改为34
    //若有多个文档,默认只更新第一个
    stuModel.update({
    
    name:'小明'},{
    
    $set:{
    
    test:34}},(err,raw)=>{
    
    
      console.log(raw)
    })
      
     //{ n: 1, nModified: 1, ok: 1 }
	 //6017befb5c36d64d08b72576	小明	68	0	34
  }
})

6.2 updateOne()

  • Model.updateOne(conditions, doc, [options], [callback])
  • Similar to update(), the only difference is that updateOne() updates one document by default, even if {multi:true} is set, it cannot only update one document

6.3 updateMany()

  • Model.updateMany(conditions, doc, [options], [callback])
  • Similar to update(), the only difference is that updateMany() updates multiple documents by default, even if {multi:false} is set, it cannot only update one document

6.4 find()+save()

for complex updates

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',err=>{
    
    
  if(!err){
    
    
     var Schema =new mongoose.Schema({
    
     name:String,grades:Number,test:{
    
    type:Number,default:0}})
     var stuModel = mongoose.model('grades',Schema)
	
     //查询成绩小于60的数据,并在其名字后添加‘:差生’字段
     stuModel.find({
    
    grades:{
    
    $lt:60}},(err,docs)=>{
    
    
      console.log(docs);
      /*[{test: 0,_id: 6017c455ba09d355a49ec8eb,name: '小红',grades: 52,__v: 0},
        {test: 0,_id: 6017c455ba09d355a49ec8ec,name: '小刚',grades: 46,__v: 0}]*/
      
      docs.forEach((item,index,arr) => {
    
    
        item.name += ':差生'
        //将修改后的数据保存
        item.save()
      })
      console.log(docs)
      /*[{test: 0,_id: 6017c455ba09d355a49ec8eb,name: '小红:差生',grades: 52,__v: 0},
        {test: 0,_id: 6017c455ba09d355a49ec8ec,name: '小刚:差生',grades: 46,__v: 0}]*/
    })
  }
})

6.5 findOne() + save()

  • for complex updates
  • The return value of findOne() is the document object
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',err=>{
    
    
  if(!err){
    
    
     var Schema =new mongoose.Schema({
    
     name:String,grades:Number,test:{
    
    type:Number,default:0}})
     var stuModel = mongoose.model('grades',Schema)
	
     //查询成绩小于60的数据,并在其名字后添加‘:差生’字段
     stuModel.findOne({
    
    name:'小明'},(err,doc)=>{
    
    
      console.log(doc);
      //{test: 34,_id: 6017c455ba09d355a49ec8eb,name: '小明',grades: 68,__v: 0},
      doc.age += 10
      doc.save()
      console.log(docs)
      //{test: 34,_id: 6017c455ba09d355a49ec8eb,name: '小明',grades: 78,__v: 0}
    })
  }
})

6.6 finOneAndUpdate()

Model.findOneAndUpdate([conditions], [update], [options], [callback])

6.7 findByIdAndUpdate()

Model.findByIdAndUpdate([conditions], [update], [options], [callback])

7. Document deletion


7.1 deleteOne()

  • All data matching the criteria will be deleted
  • Model's deleteOne()
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',err=>{
    
    
  if(!err){
    
    
     var Schema =new mongoose.Schema({
    
     name:String,grades:Number,test:{
    
    type:Number,default:0}})
     var stuModel = mongoose.model('grades',Schema)
     //删除名字中包含‘差生’的数据
	 stuModel.deleteOne({
    
    name:/差生/},function(err){
    
    })
     // 回调函数不能省略,但可以使用exec() 简写
     //stuModel.deleteOne({name:/差生/}).exec()
    })
  }
})
  • document deleteOne()
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student',err=>{
    
    
  if(!err){
    
    
     var Schema =new mongoose.Schema({
    
     name:String,grades:Number,test:{
    
    type:Number,default:0}})
     var stuModel = mongoose.model('grades',Schema)
     //删除名字中包含‘差生’的数据
	 stuModel.find({
    
    name:/差生/},function(err,docs){
    
    
         docs.forEach((item,index,arr)=>{
    
    
             item.deleteOne((err,doc)=>{
    
    
                 //doc为被删除的值
                 console.log(doc)
             })
         })
     })
    })
  }
})

7.2 findOneAndRemove()

  • Delete a piece of data that meets the conditions
  • Model.findOneAndRemove(conditions, [options], [callback])
  • The callback cannot be omitted, but the exec() shorthand can be used
stuModel.findOneAndRemove({
    
    name:/差生/}).exec()

7.3 findByIdAndRemove()

  • Delete data by id (id is unique)
  • Model.findByIdAndRemove(conditions, [options], [callback])
  • The callback cannot be omitted, but the exec() shorthand can be used

8. Front and rear hooks


  • Front and rear hooks are pre() and post() methods (middleware)
  • Middleware is specified on the schema, similar to static methods or instance methods, etc.
  • The front and back hooks can be set when doing

init validate save remove count find findOne findOneAndRemove findOneAndUpdate insertMany update

  • [pre()]: Execute before performing certain operations

  • [post]: Execute before and after certain operations are performed, and next() cannot be used

case:

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student')
var Schema =new mongoose.Schema({
    
     name:String,grades:Number,test:{
    
    type:Number,default:0}})
Schema.pre('find',function(next){
    
    
    console.log('我是pre方法1');
    next();
});
Schema.pre('find',function(next){
    
    
    console.log('我是pre方法2');
    next();
});
Schema.post('find',function(docs){
    
    
  console.log('我是post方法1');
});
Schema.post('find',function(docs){
    
    
  console.log('我是post方法2');
});  
var stuModel = mongoose.model('grades', Schema);
stuModel.find(function(err,docs){
    
    
    console.log(docs[0]);
})    
/*
我是pre方法1
我是pre方法2
我是post方法1
我是post方法2
{test: 34, _id: 6017befb5c36d64d08b72576,name: '小明',grades: 78,__v: 0}
*/

9. Document Verification


  • It is guaranteed that when saving the document, it can be set according to the fields set by the Schema

9.1 [required]: The data is required

//将name设置为必填字段,如果没有name字段,文档将不被保存,且出现错误提示
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student')
var Schema =new mongoose.Schema({
    
    
  name:{
    
    
    type:String,
    required:true
  },
  age:Number
})
var stuModel = mongoose.model('students', Schema);
new stuModel({
    
    age:20}).save((err,doc)=>{
    
    
  if(err){
    
    
    return console.log(err)
  }
  console.log(doc)
})

//报错:name: Path `name` is required.

9.2 [default]: default value

//设置age字段的默认值为18,如果不设置age字段,则会取默认值
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student')
var Schema =new mongoose.Schema({
    
    
  name:String,
  age:{
    
    
    type:Number,
    default:18
  }
})
var stuModel = mongoose.model('students', Schema);
new stuModel({
    
    name:'李雷'}).save((err,doc)=>{
    
    
  if(err){
    
    
    return console.log(err)
  }
  console.log(doc)
})

//{ age: 18, _id: 6018f3bd7e51343e6c4f212b, name: '李雷', __v: 0 }

9.3 【min】【max】: minimum/maximum value

  • only works with numbers
//将age的取值范围设置为[0,10]。如果age取值为20,文档将不被保存,且出现错误提示
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student')
var Schema =new mongoose.Schema({
    
    
  name:String,
  age:{
    
    
    type:Number,
    min:10,
    max:18
  }
})
var stuModel = mongoose.model('students', Schema);
new stuModel({
    
    name:'李雷',age:20}).save((err,doc)=>{
    
    
  if(err){
    
    
    return console.log(err)
  }
  console.log(doc)
})

//age: Path `age` (20) is more than maximum allowed value (18).

9.4 [match]: regular match

  • only works with strings
//将name的match设置为必须存在'01'字符。如果name不存在'01',文档将不被保存,且出现错误提示
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student')
var Schema =new mongoose.Schema({
    
    
  name:{
    
    type:String,match:/01/},
  age:Number,
})
var stuModel = mongoose.model('students', Schema);
new stuModel({
    
    name:'李雷',age:20}).save((err,doc)=>{
    
    
  if(err){
    
    
    return console.log(err)
  }
  console.log(doc)
})

//name: Path `name` is invalid (李雷).

9.5 [enum]: enumeration matching

  • only works with strings
//将name的枚举取值设置为['zs','ls','ww'],如果name不在枚举范围内取值,文档将不被保存,且出现错误提示
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student')
var Schema =new mongoose.Schema({
    
    
  name:{
    
    type:String,enum:['zs','ls','ww']},
  age:Number,
})
var stuModel = mongoose.model('students', Schema);
new stuModel({
    
    name:'lss',age:20}).save((err,doc)=>{
    
    
  if(err){
    
    
    return console.log(err)
  }
  console.log(doc)
})

//name: ValidatorError: `lss` is not a valid enum value for path `name`.

9.6 [validate]: custom matching

  • validate is actually a function. The parameter of the function represents the current field. Returning true means passing the validation, and returning false means failing the validation.
//定义名字name的长度必须在4个字符以上
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/student')
var Schema =new mongoose.Schema({
    
    
  name:{
    
    type:String,validate:nameLength},
  age:Number,
})
var stuModel = mongoose.model('students', Schema);
new stuModel({
    
    name:'abcd',age:20}).save((err,doc)=>{
    
    
  if(err){
    
    
    return console.log(err)
  }
  console.log(doc)
})

function nameLength(arg){
    
    
  if(arg.length>4){
    
    
    return true
  }
  return false
}

//name: Validator failed for path `name` with value `abcd`

Guess you like

Origin blog.csdn.net/weixin_43094619/article/details/131923462