2014-12-03 22 views
0
while(parentId){ 
    ancestors.push(parentId); 
    parent = Comments.findOne(parentId); 
    if(typeof parent.parentCommentId === "undefined"){ 
     break; 
    } else { 
     parentId = parent.parentCommentId; 
     console.log(parentId); 
    } 
} 

我想要這段代碼推送數組中的所有parentCommentId,直到top.But頂級評論文檔沒有字段parentCommentId。流星檢查findOne結果是否有屬性

而且我在控制檯此錯誤 Cannot read property 'parentCommentId' of undefined {stack: (...), message: "Cannot read property 'parentCommentId' of undefined"} typeof運算和hasOwnProperty不行,我怎麼能檢查屬性

+0

使用回調函數來獲取響應。 – BatScream 2014-12-03 19:02:50

回答

0

無法讀取的不確定

財產「parentCommentId」這意味着,擁有您試圖訪問的屬性的對象是未定義的,因此問題不在該屬性中。

在你的情況,似乎Comments.findOne沒有找到任何與該ID,因此parent對象是未定義的。

只要你知道,另一種方式來檢查對象的屬性的存在就是:

if (parent.parentCommentId) { 
} 
0

Comments.findOne(parentId的)可以返回不確定是否存在與ID給出結果。

parent = Comments.findOne(parentId); //parent can be undefined 
if (!parent) { 
    //parent is undefined 
} else { 
    //parent found 
} 

上面的代碼是一樣的:

parent = Comments.findOne(parentId); //parent can be undefined 
if (typeof parent === "undefined"){ 
    //parent is undefined 
} else { 
    //parent found 
} 

所以答案是:你需要檢查,如果父定義。如果是,那麼你可以訪問它的屬性。