Node.js - Mongoose路径验证失败 - TypeError:无法调用方法'验证'未定义的

时间:2014-10-10 02:15:33

标签: node.js model mongoose typeerror

我有以下Mongoose架构和路径验证:

var locationSchema = new Schema({
    userid: { type: Number, required: true },
    location: {
        type: [{
            type: "String",
            required: true,
            enum: ['Point', 'LineString', 'Polygon'],
            default: 'Point'
        }],
        coordinates: { type: [Number], required:true }

    },
    tags: [{ type: String, index: true, required: true }],
    create_date: { type: Date, default: Date.now }
});


locationSchema.path('location.coordinates').validate(function(coordinates){
        return coordinates && coordinates.toString().match(/([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/g);
}, 'Invalid latitude or longitude.');

当我启动我的应用程序时,我得到:

locationSchema.path('location.coordinates').validate(function(coordinates){
                                            ^
TypeError: Cannot call method 'validate' of undefined

任何人都可以建议为什么会失败?注意,我只是验证路径('location'),它开始没问题。

1 个答案:

答案 0 :(得分:1)

要在名为type的嵌入对象中定义字段,您需要使用显式对象表示法定义其类型,或者Mongoose认为它正在定义父对象的类型:

var locationSchema = new Schema({
    userid: { type: Number, required: true },
    location: {
        type: { type: [{
            type: "String",
            required: true,
            enum: ['Point', 'LineString', 'Polygon'],
            default: 'Point'
        }]},
        coordinates: { type: [Number], required:true }
    },
    tags: [{ type: String, index: true, required: true }],
    create_date: { type: Date, default: Date.now }
});