当前位置: 代码迷 >> 综合 >> Mongoose - 方法定义
  详细解决方案

Mongoose - 方法定义

热度:7   发布时间:2024-01-15 11:40:32.0
  • 定义Schema
let mongoose = require('mongoose'),Schema = mongoose.Schema;let UserSchema = new Schema({fullName: {// 姓名 PHARMACIST_FULLNAMEtype: String},sex: {// 性别 PHARMACIST_SEXtype: 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() 得到的实例中才能访问