【问题标题】:Console returning undefined控制台返回未定义
【发布时间】:2016-03-17 11:13:15
【问题描述】:

当我在控制台中写这个时,我得到了未定义的数据,但是数据在数据库中。我错过了什么?

Meteor.users.findOne({_id: this.userId},{fields: {"profile.pastEmployer.name": 1}});

【问题讨论】:

  • 听起来该特定用户尚未发布。
  • 我可以使用 meteortoys:allthings 看到它,所以我认为这意味着它已经发布了。
  • this.userId 指的是当前用户不是吗?
  • 不,仅在推送器和方法中。否则你应该使用Meteor.userId()
  • 这让我很头疼。我发布它只是为了确定,现在我得到了显示 userId 的对象,但不是我要求的信息

标签: meteor


【解决方案1】:

我认为您可能想要做的是:

var pastEmployerName = Meteor.user().profile.pastEmployer.name;

根据您对存在这些嵌套属性的信心程度,您可能希望像这样使用guard

var profile = Meteor.user().profile;
var pastEmployerName = profile && profile.pastEmployer && profile.pastEmployer.name;

注意事项:

  1. 使用Meteor.userId()获取当前用户的id,Meteor.user()获取当前用户的文档。在发布者和方法中,我们使用this.userId

  2. 字段投影(在您的原始问题中使用)为您提供了一个对象,包括 _id 和显示指定字段的最小结构。在您的情况下,您希望得到一个带有_idprofile 的对象,而后者又包含pastEmployer 等等。一般来说,字段投影在服务器上是有益的(它们可以节省带宽和 CPU),但在客户端上的用途有限,因为完整的文档已经在内存中。

【讨论】:

  • 谢谢大卫。这行得通。你能解释一下为什么(帮助我理解),为什么你需要使用profile && profile.pastEmployer && profile.pastEmployer.name; 而不仅仅是profile.pastEmployer.name
  • 查看有关守卫的链接文章。简而言之,如果引用的字段之一不存在,这是一种避免引发错误的方法。例如。如果您执行x.y.z 并且xy 不存在,则会引发错误。上述技术将在坏情况下安全地短路,并在良好情况下返回正确的值。
  • 对不起,我没有注意到链接。感谢您的解释,我会读一读。非常感谢您的帮助!
  • 没问题。我还应该注意,如果您确信所有用户将始终拥有必填字段,您可以使用第一行:Meteor.user().profile.pastEmployer.name
  • 大声笑。我对这些东西从来没有信心!再次感谢
猜你喜欢
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多