Mongoose - 方法定义

  • 定义Schema
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));
  • 在statics上定义方法
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();

猜你喜欢

转载自blog.csdn.net/seaalan/article/details/88105930
今日推荐