流星检查findOne结果是否有属性
问题描述:
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不行,我怎么能检查属性
答
无法读取的不确定
财产“parentCommentId”这意味着,拥有您试图访问的属性的对象是未定义的,因此问题不在该属性中。
在你的情况,似乎Comments.findOne
没有找到任何与该ID,因此parent
对象是未定义的。
只要你知道,另一种方式来检查对象的属性的存在就是:
if (parent.parentCommentId) {
}
答
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
}
所以答案是:你需要检查,如果父定义。如果是,那么你可以访问它的属性。
使用回调函数来获取响应。 – BatScream 2014-12-03 19:02:50