Getting started with mongoose (3) Mongoose index, built-in CURD method, extended static method and instance method, data validation

1. Mongoose index

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

In addition to the previous way of creating indexes in mongoose, we can also specify the creation of indexes when defining Schema.

var DeviceSchema = new mongoose.Schema({
    
     
	sn: {
    
     
		type: Number, 
		// 唯一索引 
		unique: true 
	}, 
	name: {
    
     
		type: String, 
		// 普通索引 
		index: true 
	} 
});

2. Mongoose built-in CURD

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

3. Extending the Mongoose CURD method

insert image description here
user.js under model

var mongoose = require('./db.js');

var UserSchema = mongoose.Schema({
    
    
  name: {
    
    
    type: String
  },
  sn: {
    
    
    type: String,
    index: true
  },
  age: Number,
  status: {
    
    
    type: Number,
    default: 1
  }
})
//静态方法 
UserSchema.statics.findBySn = function (sn, cb) {
    
    
  //通过 find方法获取 sn的数据    this 关键字获取当前的model
  this.find({
    
     "sn": sn }, function (err, docs) {
    
    
    cb(err, docs)
  })
}

// 实例方法   (基本不用)
UserSchema.methods.print = function () {
    
    
  console.log('我是一个实例方法')
  console.log(this.name)
}
module.exports = mongoose.model('User', UserSchema, 'user');

outermost user.js


var UserModel = require('./model/user.js');

// var user = new UserModel({
    
    
//     name: '赵六',
//     sn:'123456781',
//     age: 29
// });
// user.save();


// UserModel.findBySn('123456781',function(){})

UserModel.findBySn('123456782', function (err, docs) {
    
    
  if (err) {
    
    
    console.log(err);
    return;
  }
  console.log(docs)
})

var user = new UserModel({
    
    
  name: '赵六',
  sn: '123456781',
  age: 29
});
// user.save();
user.print();   //自定义的实例方法

Fourth, Mongoose data verification

1. Mongoose verification parameters

required : indicates that the data must be passed
in max: for Number type data, maximum value
min: for Number type data, minimum value
enum: enumeration type, the data must meet the enumeration value
enum: ['0', '1 ', '2'] match: The added data must conform to the rules of match (regular) maxlength: maximum length
minlength: minimum length

var mongoose = require('./db.js');

//mongoose数据校验:用户通过mongoose给mongodb数据库增加数据的时候,对数据的合法性进行的验证
//mongoose里面定义Schema:字段类型,修饰符、默认参数 、数据校验都是为了数据库数据的一致性

//Schema,为数据库对象的集合,每个schema会映射到mongodb中的一个collection,定义Schema可以理解为表结构的定义
var UserSchema = mongoose.Schema({
    
    
  name: {
    
    
    type: String,//指定类型
    trim: true,   //修饰符         
    required: true  //这个字段必须传入
  },
  sn: {
    
    
    type: String,
    index: true,  //索引.
    set (val) {
    
      //自定义修饰符
      return val;
    },
    // maxlength:20,
    // minlength:10
    // match:/^sn(.*)/ ,
    validate: function (sn) {
    
    
      return sn.length >= 10;
    }
  },
  age: {
    
    
    type: Number,
    min: 0,    //用在number类型上面,最小0
    max: 150   //最大150
  },
  status: {
    
    
    type: String,
    default: 'success', //默认值
    enum: ['success', 'error']   //status的值必须在 对应的数组里面  注意枚举是用在String
  }
})

module.exports = mongoose.model('User', UserSchema, 'user');



2. Mongoose custom validator

desc: {
    
     
	type: String, 
	// 自定义的验证器,如果通过验证返回 true,没有通过则返回 false 
	validate: function(desc) {
    
     
		return desc.length >= 10; 
	} 
}

Guess you like

Origin blog.csdn.net/qq_41880073/article/details/122897015