let mongoose = require('mongoose'),
Schema = mongoose.Schema;
let UserSchema = new Schema({
fullName: {// 姓名 PHARMACIST_FULLNAME
type: String
},
sex: {// 性别 PHARMACIST_SEX
type: String,
enum: ['男', '女']
}
}, {timestamps: {createdAt: 'created', updatedAt: 'updated'}});
- 在methods上定义方法(Schema.methods.fn)
UserSchema.methods = {
authenticate(plainPassword) {
return this.password === this.hashPassword(plainPassword);
},
hashPassword: function (password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, new Buffer(this.salt, 'base64'), 10000, 64, 'sha1').toString('base64');
} else {
return password;
}
}
};
- 使用方式,只能在 new Model() 得到的实例中才能访问
User.get(user._id)
.then((user) => {
let isUser = user.authenticate(oldPass);
return user.save();
})
.catch(err => next(err));
UserSchema.statics = {
checkPhone: (phone) => {
if(!(/^[1][3,4,5,7,8]\d{9}$/.test(phone))){
return false
}else{
return true;
}
},
randomCode: () => {// 返回由1~9组成的4位随机码,不包括0
let code = "";
for(let i = 0; i < codeLen; i++){
code += Math.floor(Math.random()*9 + 1)
}
console.info(code);
return code;
}
};
User.randomCode();