【问题标题】:Weird undefined error on server服务器上奇怪的未定义错误
【发布时间】:2015-01-31 05:47:18
【问题描述】:

我有以下流星方法

hasNoPendingPayments: function() {
    var userId = Meteor.userId();
    console.log(userId); <---------------------- correctly logs userId
    var user   = Users.findOne({_id: userId }, { fields: { services: 0 } });
    console.log(user); <-------------------------- logs 'undefined'
    return hasNoPendingPayments(user);
  },

我从上面调用的这个私人助手

hasNoPendingPayments = function(user) {
  // console.log('hasNoPendingPayments ');
  // console.log(user);
  var payments = Payments.find({ userId: user._id, status: {
    $in: [Payments.States.PENDING, Payments.States.PROCESSING]}
  });

  return payments.count() === 0;
};

我在这里从客户端调用它

Template.payments.created = function() {
  this.hasNoPendingPayments      = new ReactiveVar(false);v
};

Template.payments.rendered = function () {
  Session.set('showPaymentRequestForm', false);

  var self = this;
  Meteor.call('hasNoPendingPayments', function(error, result) {
    if (result === true) { self.hasNoPendingPayments.set(true); }
  });
  ...

但是,当我最初加载模板时,我在服务器上收到了一个未定义的错误(我在代码中标记了位置)。虽然,当我尝试使用相同的 userId 在客户端上调用相同的查询时,我正确地获取了用户记录

知道这是为什么吗?

【问题讨论】:

  • 我们确定用户在payments模板渲染的时候已经登录了吗?如果他/她正在登录,那么你可能会得到这种行为。

标签: meteor


【解决方案1】:

试试这个。

Template.payments.rendered = function () {
  Session.set('showPaymentRequestForm', false);

  var self = this;
if(Meteor.userId()){
  Meteor.call('hasNoPendingPayments', function(error, result) {
    if (result === true) { self.hasNoPendingPayments.set(true); }
  });
}else{
console.log("Seems like user its not logged in at the moment")
}

也许当你进行 Meteor.call 时,数据还没有准备好

还只是为了确定,当您在 console.log 上运行 Users.findOne({_id: userId }, { fields: { services: 0 } }); 时会得到什么?

可能是查找错误或有错别字

更新

Router.map(function() 
    {
    this.route('payments', 
        {
        action: function() 
            {
            if (Meteor.userId())
                this.render();
            } else{
                this.render('login') // we send the user to login Template
         }
        }
    }

waitOn

Router.map(function () {
  this.route('payments', {
    path: '/payments',
    waitOn: function(){
        return Meteor.subscribe("userData"); //here we render template until the subscribe its ready
    }
  });
}); 

【讨论】:

  • 你说得对,最初我没有登录。findOne 返回 Object {_id: "Co5bMySeaqySgDP6h", emails: Array[1], profile: Object,income: Object}
  • 请使用 if(Meteor.userId()){},因为您在模板渲染时调用该方法,让我们确保 Meteor.call 仅在我们有用户登录时运行
  • 确实如此,这就是问题所在。使用 Iron-router 渲染模板时,确保 Meteor.user() 准备就绪的最佳方法是什么?
【解决方案2】:

Meteor 将所有用户记录存储在Meteor.users 集合中

所以试试Meteor.users.findOne({_id: userId }....)

而不是Users.findOne({_id: userId }, { fields: { services: 0 } });

在你的服务器方法中

【讨论】:

  • 我忘了提,但我将集合句柄存储在一个全局变量中,例如 Users = Meteor.users;我想这是不可能的?
猜你喜欢
  • 2010-12-20
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多