我发布多用户信息(使用Meteor.users集合)以命名帖子创建者,并将他们的名字和其他小细节与这些帖子相关联,但我不想为每个用户发布完整的文档因为他们有“秘密”的登录信息。
以下是我正在使用的代码:
Meteor.publish("serverforumthread", function(thread){
check(thread, String);
var replies = forumReplies.find({thread: thread});
var users = {};
replies.map(function(r){
users[r.owner] = r.owner;
});
var userids = _.map(users, function(value, key){ return value; });
var projectedFields = {_id:1, username:1, forumStats: 1, services: 0};
var usrs = Meteor.users.find({_id:{$in: userids}}, projectedFields);
var anyUpdateToUsers = false;
usrs.map(function(owner){
var changed = false;
if(!owner.username){
owner.username = owner.emails[0].address.split("@")[0];
changed = true;
}
//owner.forumStats = undefined;
if(!owner.forumStats){
owner.forumStats = {};
owner.forumStats.postCount = 0;
owner.forumStats.postLikes = 0;
owner.forumStats.title = "the newbie";
owner.forumStats.tag = "newbie";
owner.forumStats.img = "http://placehold.it/122x122";
changed = true;
}
if(changed){
anyUpdateToUsers = true;
Meteor.users.update({_id: owner._id}, {$set:{ forumStats:owner.forumStats }});
}
});
if(anyUpdateToUsers) // refresh it
usrs = Meteor.users.find({_id:{$in: userids}}, projectedFields);
usrs.map(function(owner){
console.log(owner);
});
return [replies, usrs];
});
正如您所看到的,我只对发布线程及其关联用户用户名和小型forumStats的依赖(帖子)感兴趣,我希望将“服务”密钥保密,因为它包含不应发布的详细信息
“console.log”的示例输出:
{ _id: 'hoRYFbRkXXbHYm8Ty',
createdAt: Tue Jun 03 2014 16:25:42 GMT+0100 (WEST),
emails: [ { address: 'somemail@gmail.com', verified: false } ],
forumStats:
{ postCount: 85,
postLikes: 5,
title: 'the newbie',
tag: 'newbie',
img: 'http://placehold.it/122x122' },
services:
{ password: { srp: [Object] },
resume: { loginTokens: [Object] } } }
我做错了什么?
谢谢。
答案 0 :(得分:1)
请查看文档field specifiers部分中的示例,并尝试一下:
var projectedFields = {fields: {username:1, forumStats: 1}};
您将免费获得_id
,并且只会包含您指定的其他字段。请注意,您无法混合包含和排除选项,这意味着您不能同时拥有0和1。
如果这不起作用,请告诉我,我会更仔细一点。