2016-03-07 66 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