【问题标题】:Meteor.users subscribe only return current userMeteor.users 订阅只返回当前用户
【发布时间】:2015-07-24 17:19:26
【问题描述】:

我试图通过用户名获取用户,当我使用Meteor.users.findOne 时,它总是返回当前用户。如果我使用Meteor.users.find,它将返回所有当前用户文档,以及正确匹配用户名的profile.firstNameprofile.lastName

Meteor.publish('userByUsername', function(username) {
    return Meteor.users.findOne({
        username: username
    }, {
        fields: {
            'profile.firstName': 1,
            'profile.lastName': 1,
        }
    });
});

如何只获取与用户名匹配的用户?

【问题讨论】:

    标签: angularjs meteor angular-meteor


    【解决方案1】:

    我认为您想要的不是发布,而是访问特定用户名的方法。发布/订阅非常适合经常更改的数据集 - 例如 stackoverflow、Facebook 提要、新闻文章等上的帖子。

    您正在寻找特定用户的名字/姓氏,这并没有真正改变。所以你真正想要的是创建一个返回用户名/姓的服务器方法。您可以从客户端调用此方法来访问这些数据。

    if (Meteor.isClient) {
    
      //get username var
      Meteor.call('findUser', username, function(err, res) {
        console.log(res.profile.firstName + " " + res.profile.lastName);
      });
    
    }
    
    if (Meteor.isServer) {
    
      Meteor.methods({
        findUser: function(username) {
          return Meteor.users.findOne({
            username: username
          }, {
            fields: {
              'profile.firstName': 1,
              'profile.lastName': 1
            }
          });
        }
      });
    
    }
    

    注意客户端 Meteor.call 有一个回调方法。 Meteor 服务器上的 DB 查询是异步且非阻塞的,因此您需要通过 javascript 回调函数访问结果。

    【讨论】:

    • 这很好用。这是一个初学者的错误,现在用户方法和公共/订阅时我很清楚。非常感谢!
    【解决方案2】:

    findOne 查找并返回与选择器匹配的第一个文档。 Publish方法需要返回一个游标,需要使用find,而不是findOne:

    Meteor.publish('userByUsername', function(username) {
        return Meteor.users.find({
            username: username
        }, {
            fields: {
                'profile.firstName': 1,
                'profile.lastName': 1,
            }
        });
    });
    

    然后就可以在客户端调用subscribe了:

    Meteor.subscribe('userByUsername', 'bob');
    

    例如,在你的助手中调用Meteor.users.findOne({ username: 'bob' });

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 1970-01-01
      • 2022-08-09
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 2012-08-31
      • 2015-01-27
      • 2017-03-28
      相关资源
      最近更新 更多