在模板助手中使用Meteor.users()

时间:2014-04-01 17:32:44

标签: collections meteor meteor-blaze meteor-helper

我遇到了从Meteor 0.8.0中的模板助手中获取用户个人资料数据的问题。这段代码在之前的版本中运行良好,但自从今天早上升级以来它就被打破了。我原本以为这是模板助手运行两次的问题,但是当我深入研究时,我发现这个问题比那更麻烦。

在模板助手'findClientLiason'下面调用两次(它的输出在控制台中记录为2x)。第一次用户将第二次显示为“未定义”,第二次正确的用户对象将通过我期望的方式。两次'clientLiason'都会正确输出。

对我来说最有趣的是,如果我删除'var user = Meteor.users.findOne({_ id:clientLiason});'调用getOne调用helper只调用一次。

在我看来,对Meteor.users集合的调用强制另一次调用数据库。而第一次调用它时,Meteor.users集合是空的。

我的出版物和订阅如下所示。我正在使用Iron Router全局waitOn()函数,但我想知道是否应该提前加载Meteor.users集合?

任何想法都将不胜感激。再次感谢。

publications.js

Meteor.publish('allUsers', function() {
    return Meteor.users.find();
});

router.js

Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    waitOn: function() { 
        return [    
            Meteor.subscribe('clientsActive'),
            Meteor.subscribe('allUsers'),
            Meteor.subscribe('notifications')
        ];
}
});

clientItem.html

<template name="clientItem">
    {{findClientLiason clientLiason}}
</template>

clientItem.js

Template.clientItem.helpers({
    findClientLiason: function(clientLiason) {
        var user = Meteor.users.findOne({_id: clientLiason});
        console.log(clientLiason);
        console.log(user);
        return user.profile.name;
    }
});

1 个答案:

答案 0 :(得分:4)

这是有道理的,因为正在发生的事情是,首先在页面加载时呈现模板,并且用户集合为空,然后在数据更改时重新呈现模板(例如,填充本地mongo集合)

您应该编写模板,以期在没有数据的情况下从页面加载开始。我会把助手改成这样的东西:

findClientLiaison: function(clientLiaison) {
  var user = Meteor.users.findOne(clientLiaison);
  if (user) {
    return user.profile.name;
  }
  return "no data yet";
}
相关问题