2016-05-18 41 views
0

這個錯誤非常古怪。它並不總是失敗,但是當它看起來像這樣。Mongoose ValidationError需要超出子文檔數組邊界的路徑

我有一些代碼可以改變子代文件數組中元素的「代碼」(一個字符串)。它貫穿每個目標,檢查是否有要應用的更改,如果有,應用它。

for (i = 0; i < user.goals.length; i++) { 
    if (transformsMap[user.goals[i].code]) { 
    user.goals[i].code = transformsMap[user.goals[i].code] 
    } 
} 
user.goals.sort(function (a,b) {return a.code.charCodeAt(0) - b.code.charCodeAt(0)) 

當我保存它,有時我得到這樣的錯誤:

'goals.3.code': 
    { [ValidatorError: Path `code` is required.] 

...但3在這種情況下,是目標陣列的長度。即沒有目標.3子文檔。我已經在驗證之前嘗試記錄user.goalsuser.goals.length,他們都同意數組中只有3個元素。

我完全不知所措。

+3

不幸的是,這將是艱難的幫助,除非你能提供一個[MCVE。 – JohnnyHK

回答

0

如何添加更多支票?如果if子句失敗,還要設置默認值?

for (i = 0; i < user.goals.length; i++) { if (user.goals[i] && user.goals[i].code && transformsMap[user.goals[i].code]){ user.goals[i].code = transformsMap[user.goals[i].code] } else { user.goals[i].code = "" // Whatever this is <-- default value. } } user.goals.sort(function (a,b) {return a.code.charCodeAt(0) - b.code.charCodeAt(0))

+0

我已經添加了檢查,並且在保存之前的檢查結果顯示數組中仍然只有例如3個項目,並且問題出現在第四個項目中。 – MalcolmOcean