【发布时间】:2018-07-08 03:10:58
【问题描述】:
我已经定义了一个猫鼬模式和类,但是在预验证钩子中,this 上下文是空的。我收到TypeError: this.validateColor is not a function
bike.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Mongodb Object Model
// =============================================================================
let BikeSchema = new Schema({
color: {
type: String,
required: true
},
wheels: {
type: Number,
required: true
}
});
// Bike Class
// =============================================================================
class BikeClass {
validateColor() {
if(this.color !== 'blue' && this.color != 'red') {
this.invalidate('Not a valid color');
}
}
validateWheels() {
if(this.wheels < 2 || this.wheels > 3) {
this.invalidate('Not a valid number of wheels');
}
}
}
BikeSchema.loadClass(BikeClass);
// Do validation checks as API hooks
BikeSchema.pre('validate', next => {
// Problem: this = {}
this.validateColor();
this.validateWheels();
next();
});
module.exports = mongoose.model('Bike', BikeSchema);
index.js
const Bike = require('./bike.js');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bikes');
const db = mongoose.connection;
// Connect to Mongo db
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.debug('Connected to mongo successfully');
let bike = new Bike();
bike.color = 'red';
bike.wheels = 1;
bike.save()
.catch(err => {
console.error(err);
})
});
【问题讨论】: