Mongoose SchemaString#match接收TypeError

时间:2016-03-07 22:44:56

标签: regex node.js mongodb mongoose

我目前正在尝试使用正则表达式在Node.js中执行模式匹配,并且相信所有内容都是根据正确的Mongoose文档设置的,但是当我尝试验证正则表达式时,它无法执行此操作。我使用以下内容作为我的Mongoose Schema:

var dateTimeMatch = ['/-?[0-9]{4}(-(0[1-9]|1[0-2])(-(0[0-9]|[1-2][0-9]|3[0-1])))(T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00)))/', 'Deceased DateTime must be in the format: 1992-12-31T23:59:59+14:00'];

module.exports = mongoose.model('Patient', new Schema({
    identifier: [{
        period: {
            start: { type: String, match: dateTimeMatch, required: true},
            end: {type: String, match: dateTimeMatch} //if not ongoing
        }
 }]
});

我使用以下JSON作为有效负载:

{
    "identifier":{
        "period":{
            "start":"1992-12-31T23:59:59+14:00"
        }
    }
}

我正在尝试使用以下代码将模型保存到MongoDB本身,这似乎也是正确的。

 //Build Mongoose Model for insertion into DB
    var patientBody = new Patient(req.body);
    //patientBody.affiliation = Lookup from UID what company affiliation *TODO
    patientBody.save(function(err) {
        console.log(err);
 }

但最终我收到以下错误:

\node_modules\mongoose\lib\schema\string.js:357
        ? regExp.test(v)
                 ^
TypeError: undefined is not a function
    at EmbeddedDocument.matchValidator (\node_modules\mongoose\lib\schema\string.js:357:18)
    at \node_modules\mongoose\lib\schematype.js:724:28
    at Array.forEach (native)
    at SchemaString.SchemaType.doValidate (\node_modules\mongoose\lib\schematype.js:698:19)
    at \node_modules\mongoose\lib\document.js:1191:9
    at process._tickCallback (node.js:355:11)

Process finished with exit code 1

我相信我已经将问题缩小到了正确无法正确验证的正则表达式,但我不确定为什么或如何进一步纠正这个问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

正则表达式需要是一个实际的正则表达式对象而不是字符串。

试试这个:

var dateTimeMatch = [
  /-?[0-9]{4}(-(0[1-9]|1[0-2])(-(0[0-9]|[1-2][0-9]|3[0-1])))(T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?(Z|(\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00)))/,
  'Deceased DateTime must be in the format: 1992-12-31T23:59:59+14:00'
];