发布整个Meter.users集合

Nat*_*ate 0 meteor

我试图将所有Meteor.users发布到一个People集合中.我的发布函数看起来就像文档中的那个,除了我没有指定要发布的字段:

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

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

sbk*_*ing 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();
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

请注意,我只在这里发布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();
});
Run Code Online (Sandbox Code Playgroud)