TypeError:无法读取属性' path'在Mongoose 4.0.3中未定义

时间:2015-07-02 20:38:35

标签: node.js mongoose

我试图为猫鼬计划添加一些验证器。我的模型看起来像:

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

我做错了什么?

1 个答案:

答案 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');