Mongoose 索引 内置方法 静态方法和实例方法
添加索引
-
const UserSchema = mongoose.Schema({ name: { type: String }, sn: { type: String, index: true, // 添加索引 }, age: Number, status: { type: Number, default: 0 } })
扩展静态方法
-
UserSchema.statics.findBySn = function (sn, cb) { // 通过 find 方法获取 sn 的数据 this.find({ sn }, function (err, docs) { cb(err, docs) }) }
将静态方法挂载到 Schema.statics 对象上
扩展实例方法
-
UserSchema.methods.print = function () { console.log('我是一个实例方法', this) }
将实例方法挂载到 Schema.methods 对象上