Meteor / Mongo:$不能检索用户组

时间:2016-02-25 09:15:31

标签: mongodb meteor

我正在尝试返回当前用户所属的所有组。每个用户都有一个groups字段,它只是用户所属组的id数组。这是我的代码的样子:

我的用于返回正确组的服务器方法

userGroups: function(){
    var currentUser = Meteor.users.find({_id: Meteor.userId()});
    return Groups.find({_id: { $in: currentUser.groups}});
}

然后在我的助手中调用该方法:

groups: function(){
    return Meteor.call('userGroups');
}

我已经尝试在控制台中调试它,但我只是变得更加困惑。我可以调用var user = Meteor.users.find(_id: Meteor.userId())并正确地将当前用户分配给变量,但是当我调用user.groups(这是组ID的数组)时,它表示它是未定义的。如果我在meteor mongo命令行界面中检查文档,则当前用户有一个组字段,其中包含组ID。

1 个答案:

答案 0 :(得分:0)

在Meteor中查找查询返回的游标不是数组,而是一个对象。

您应该添加.fetch()或使用findOne()。

userGroups: function(){
    var currentUser = Meteor.users.findOne({_id: Meteor.userId()});
// or use var currentUser = Meteor.users.find({_id: Meteor.userId()}).fetch();
    return Groups.find({_id: { $in: currentUser.groups}});
}

这应该有效!

发布组的更新形成Meteor.users集合

要将Meteor.users集合中的组添加到acccounts-password包中的Meteor.user()自动发布,您需要将其包含在空发布中。

这样的事情:

Meteor.publish(null, function () {
        if (!this.userId) return this.ready();
        return Meteor.users.find({_id: this.userId}, {
            fields: {
                profile : 1,
                emails  : 1,
                groups  : 1
            }
        });
    });