首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Meteor检查findOne结果是否具有属性

Meteor检查findOne结果是否具有属性
EN

Stack Overflow用户
提问于 2014-12-03 23:59:22
回答 2查看 912关注 0票数 0
代码语言:javascript
代码运行次数: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为止。

我在控制台中遇到这个错误,typeof Cannot read property 'parentCommentId' of undefined {stack: (...), message: "Cannot read property 'parentCommentId' of undefined"} hasOwnProperty不起作用,我如何检查属性

EN

回答 2

Stack Overflow用户

发布于 2014-12-04 00:37:09

无法读取未定义的属性“”parentCommentId“”

这意味着拥有您试图访问的属性的对象是未定义的,因此问题不在于该属性。

在您的示例中,Comments.findOne似乎没有找到具有该id的任何内容,因此parent对象是未定义的。

如您所知,检查对象中是否存在属性的另一种方法是:

代码语言:javascript
代码运行次数:0
运行
复制
if (parent.parentCommentId) {
}
票数 0
EN

Stack Overflow用户

发布于 2014-12-04 02:04:56

如果没有给定ID的结果,Comments.findOne(parentId)可以返回undefined。

代码语言:javascript
代码运行次数:0
运行
复制
parent = Comments.findOne(parentId); //parent can be undefined
if (!parent) {
    //parent is undefined
} else {
    //parent found
}

上面的代码与:

代码语言:javascript
代码运行次数:0
运行
复制
parent = Comments.findOne(parentId); //parent can be undefined
if (typeof parent === "undefined"){
    //parent is undefined
} else {
    //parent found
}

因此,答案是:您需要检查是否定义了parent。如果是,则可以访问其属性。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27276172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档