发布整个Meter.users集合

时间:2014-12-19 17:39:13

标签: meteor

我正在尝试将所有Meteor.users发布到People集合。我的发布功能看起来就像文档中的那个,除了我没有指定要发布的字段:

Meteor.publish("people", function () {
  if (this.userId) {
    console.log(Meteor.users.find({}).count());
    return Meteor.users.find();
  } else {
    this.ready();
  }
});

console.log打印80所以我知道有用户。但是,当我在我的客户端上查询People.find().count()时,它会返回0。我做错了什么,谢谢。

2 个答案:

答案 0 :(得分:5)

实际上很有可能将用户发布到客户端的其他集合。但是你必须亲自动手并使用低级别的观察和发布API。例如:

if (Meteor.isClient) {
  // note this is a client-only collection
  People = new Mongo.Collection('people');

  Meteor.subscribe('people', function() {
    // this function will run after the publication calls `sub.ready()`
    console.log(People.find().count()); // 3
  });
}

if (Meteor.isServer) {
  // create some dummy users for this example
  if (Meteor.users.find().count() === 0) {
    Accounts.createUser({username: 'foobar', password: 'foobar'});
    Accounts.createUser({username: 'bazqux', password: 'foobar'});
    Accounts.createUser({username: 'bonker', password: 'foobar'});
  }

  Meteor.publish('people', function() {
    var sub = this;

    // get a cursor for all Meteor.users documents
    // only include specified fields so private user data doesn't get published
    var userCursor = Meteor.users.find({}, {
      fields: {
        username: 1,
        profile: 1
      }
    });

    // observe changes to the cursor and propagate them to the client,
    // specifying that they should go to a collection with the name 'people'
    var userHandle = userCursor.observeChanges({
      added: function(id, user) {
        sub.added('people', id, user);
      },
      changed: function(id, fields) {
        sub.changed('people', id, fields);
      },
      removed: function(id) {
        sub.removed('people', id);
      }
    });

    // tell the client that the initial subscription snapshot has been sent.
    sub.ready();

    // stop observing changes to the cursor when the client stops the subscription
    sub.onStop(function() {
      userHandle.stop();
    });
  });
}

请注意,我只在此处发布usernameprofile字段:您想要发布整个用户文档,因为它会发送私人信息,例如他们的密码哈希,第三方服务信息等

请注意,您也可以使用此方法将已发布的用户分隔为不同的任意命名的客户端集合。您可能拥有AdminUsers集合,BannedUsers集合等。然后,您可以选择性地将同一MongoDB(服务器)集合中的文档发布到不同的Minimongo(客户端)集合。

编辑:我意识到有一个名为Mongo.Collection._publishCursor的无证流星特征,它在我的例子中完成了发布函数中的大部分内容。因此,您实际上可以像这样重写该出版物,它将完全相同,将Meteor.users文档发布到客户端'people'集合:

Meteor.publish('people', function() {
  var userCursor = Meteor.users.find({}, {
    fields: {
      username: 1,
      profile: 1
    }
  });

  // this automatically observes the cursor for changes,
  // publishes added/changed/removed messages to the 'people' collection,
  // and stops the observer when the subscription stops
  Mongo.Collection._publishCursor(userCursor, this, 'people');

  this.ready();
});

答案 1 :(得分:0)

您是否定义了名为People的集合?仅仅因为您的发布功能被命名为“人”并不意味着有一个名为People的流星集合。

听起来像你需要定义一个名为People的mongo集合并填充它,或者你应该从客户端查询Meteor.users集合 - 因为你要返回Meteor.users.find()