【问题标题】:Updating MongoDB in Meteor Router Filter Methods在 Meteor Router 过滤器方法中更新 MongoDB
【发布时间】:2013-07-15 01:46:07
【问题描述】:

我目前正在尝试通过存储 userId、Meteor.Router.page() 和用户点击其他页面时的时间戳来记录流星应用中的用户页面浏览量。

//userlog.js
Meteor.methods({
  createLog: function(page){
    var timeStamp = Meteor.user().lastActionTimestamp;
    //Set variable to store validation if user is logging in
    var hasLoggedIn = false;
    //Checks if lastActionTimestamp of user is more than an hour ago
    if(moment(new Date().getTime()).diff(moment(timeStamp), 'hours') >= 1){
      hasLoggedIn = true;
    }
      console.log("this ran");

    var log = {
      submitted: new Date().getTime(),
      userId: Meteor.userId(),
      page: page,
      login: hasLoggedIn
    }

    var logId = Userlogs.insert(log);

    Meteor.users.update(Meteor.userId(), {$set: {lastActionTimestamp: log.submitted}});
    return logId;
  }
});

//router.js This method runs on a filter on every page
'checkLoginStatus': function(page) {
    if(Meteor.userId()){
      //Logs the page that the user has switched to
      Meteor.call('createLog', page);
      return page;
    }else if(Meteor.loggingIn()) {
      return 'loading';
    }else {
      return 'loginPage';
    }
  }

但这不起作用,最终会递归创建用户日志。我相信这是因为我在路由器过滤方法中做了一个 Collection.find 。有没有人可以解决这个问题?

【问题讨论】:

    标签: mongodb meteor meteorite


    【解决方案1】:

    当您更新Meteor.users 并设置lastActionTimestamp 时,Meteor.user 将被更新并将失效信号发送到所有依赖它的反应上下文。如果在过滤器中使用了Meteor.user,则该过滤器和所有连续的过滤器,包括checkLoginStatus 将重新运行,从而导致循环。

    我发现的最佳做法:

    1. 尽量避免在过滤器中使用反应式数据源。

    2. 尽可能使用Meteor.userId(),而不是Meteor.user()._id,因为前者不会在用户对象的属性更改时触发失效。

    3. 对过滤器进行排序,以便它们首先使用更新最频繁的反应数据源运行。例如,如果您有一个需要用户的 trackPage 过滤器,则让它在另一个名为 requireUser 的过滤器之后运行,以便在跟踪之前确定您有一个用户。否则,如果您先跟踪,然后检查用户,然后当 Meteor.logginInfalse 更改为 true 时,您将再次跟踪页面。

    这是我们切换到meteor-mini-pages 而不是 Meteor-Router 的主要原因,因为它更容易处理响应式数据源。过滤器可以redirect,它可以stop()路由器停止运行等。

    最后,cmather 和其他人正在开发一种新的路由器,它是迷你页面和 Meteor.Router 的合并。它将被称为 Iron Router,我建议在它推出后使用它!

    【讨论】:

      猜你喜欢
      • 2022-12-22
      • 2017-05-08
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多