2016-03-07 22 views
0

我目前正在尝试使用正则表达式在Node.js中执行模式匹配,并认为一切都是根据适当的Mongoose文档设置的,但是当我尝试验证正则表达式时,它未能这样做。我使用我的猫鼬架构如下:Mongoose SchemaString#匹配接收TypeError

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

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

试试这个:

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' 
]; 
+0

啊,就是这样!非常感谢! – Kyle