我试图为猫鼬计划添加一些验证器。我的模型看起来像:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Usr = new Schema({
_id: { type: String },
email1: { type: String },
password: { type: String },
admin: { type: Boolean },
firstName: { type: String },
lastName: { type: String },
hasCar: { type: Boolean },
phone: { type: Number }
});
Usr.schema.path('email1').validate(function (value) {
return /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.test(value);
}, 'Invalid email');
module.exports = mongoose.model('User', Usr);
但是我得到了一个TypeError:
Usr.schema.path('email1').validate(function (value) {
^
TypeError: Cannot read property 'path' of undefined
我做错了什么?
答案 0 :(得分:1)
Usr
本身就是一个Schema对象。所以:
Usr.path('email1').validate(function (value) {
return /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.test(value);
}, 'Invalid email');