【问题标题】:Node.js - Mongoose path validation failing - TypeError: Cannot call method 'validate' of undefinedNode.js - Mongoose 路径验证失败 - TypeError:无法调用未定义的方法“验证”
【发布时间】:2014-12-05 02:55:41
【问题描述】:

我有以下 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

谁能告诉我为什么会失败?请注意,我只是验证路径('位置'),它开始正常。

【问题讨论】:

    标签: node.js model mongoose typeerror


    【解决方案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 }
    });
    

    【讨论】:

    • 感谢@JohnnyHK 让我难过!!
    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2019-12-15
    • 2013-08-15
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多