我正在尝试将所有的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。我做错什么了谢谢。
发布于 2014-12-19 20:01:36
实际上,很可能在客户端将用户发布到不同的集合中。但是你必须弄脏你的手,使用低级别的观察和发布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();
});
});
}请注意,我只在这里发布username和profile字段:您不希望发布整个用户文档,因为它将发送私有信息,如密码哈希、第三方服务信息等。
注意,您也可以使用此方法将已发布的用户分离到不同的任意命名的客户端集合中。您可能有一个AdminUsers集合、一个BannedUsers集合等等。然后您可以选择性地将文档从同一个MongoDB (服务器)集合发布到不同的Minimongo (客户端)集合。
编辑:我意识到有一个名为Mongo.Collection._publishCursor的无文档化的Meteor特性,它在我的示例中完成了发布函数中的大部分内容。因此,您实际上可以这样重写该发布,它将完全相同地工作,将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();
});发布于 2014-12-19 18:08:44
您定义了一个名为People的集合吗?仅仅因为您的发布函数名为"people“,并不意味着有一个名为People的流星集合。
在我看来,您需要定义一个名为People的mongo集合并填充它,或者您应该从客户端查询Meteor.users集合--因为您正在返回Meteor.users.find()。
https://stackoverflow.com/questions/27571169
复制相似问题