const mongoose = require("./db");
const UserSchema = mongoose.Schema({
name: {
type: String,
trim: true
},
age: Number,
sn: {
type: String,
default: "123456",
index: true //设置sn为索引
},
status: {
type: Number,
default: 1
}
});
// 静态方法
UserSchema.statics.findBySn = function(sn, cb) {
this.find({ sn }, cb);
};
// 实例方法
UserSchema.methods.print = function() {
console.log(this);
};
const UserModel = mongoose.model("User", UserSchema, "user");
module.exports = UserModel;
const UserModel = require("./model/user");
const user = new UserModel({
name: "LittleFinger",
age: 33,
status: 1,
sex: "男"
});
// 实例方法的调用
user.print();
// 静态方法的调用
UserModel.findBySn("123456", (err, docs) => {
if (err) {
console.log(err);
return;
}
console.log(docs);
});
网友评论