9. mongoose 索引及静态实例方法
1. 索引
索引是对数据库表中一列或多列的值进行排序的一种结构,可以让我们查询数据库变得更快。mongoose中,还可以在定义Schema的时候指定创建索引
var DeviceSchema = new mongoose.Schema({sn: {type: Number,unique: true // 唯一索引},name: {type: String,index: true // 普通索引}});
2. 内置CURD方法
详见文档
3. 手动扩展方法
// user.js中var mongoose = require('./db.js');var UserSchema = mongoose.Schema({name: { type: String },age: Number,status: {type: Number,default: 1}});// 静态方法UserSchema.statics.findByUid = function (uid, cb) {this.find({ _id: uid }, function (err, docs) {cb(err, docs);});}; // 实例方法UserSchema.methods.print = function () {console.log('这是一个实例方法');console.log(this);};module.exports = mongoose.model('User', UserSchema, 'user');
// 使用时const UserModel = require('./user.js')UserModel.findByUid('123123', (err, res) => {})const zs = new UserModel({name: '张三', age: 5})zs.print()
