MeteorJs查找具有用户ID数组的所有用户

时间:2017-03-03 00:50:31

标签: mongodb meteor mongoose

如何让每个在用户ID数组中拥有ID的用户。 我的问题是我有一个组的集合,每个组都有一个名为users的userID数组,这些用户属于该组,我需要知道如何从UserID的数组中获取用户对象的最佳方式要做到这一点?

客户端

export default createContainer((props) => {
  let user = Meteor.users.findOne(Meteor.userId())
  let groupsSub = Meteor.subscribe('groups')

  if (user) {
    let code = user.profile.selectedGroup
    let group = Groups.findOne({code})
    return {
      ready: groupsSub.ready(),
      group,
      users: Meteor.users.find({_id: {$in: group.users}}).fetch()
    }
  }

  return {}
}, HomePage)

服务器

 Meteor.publish('groups', function () {
 return Groups.find({
   users: {
     $elemMatch: { $eq: this.userId }
   }
 })
})

这就是我试图吸引用户的地方

   render () {
    if (this.props.ready) {
    let group = this.props.group
    let users = this.props.users
    console.log(users)

    return (
      <div className='c-fit-group'>
        <div className='c-fit-group__header'>
          <h1>{group.name}</h1>
        </div>
      </div>
     )
   }

   return <div>Loading...</div>
  }
}

我也在使用React作为前端

当我在console.log group.users时,我得到了这个 enter image description here

当我在console.log用户时,我得到了这个 enter image description here

2 个答案:

答案 0 :(得分:3)

如果您只是拥有一个用户ID数组(我无法确定您是否正在尝试解决这些问题),您可以使用$ in运算符。 e.g。

let userIds = ['abc', 'def', 'hgi'];
let userCursor = Meteor.users.find({_id: {$in: userIds}});

只获取结果而不是光标:

let userResults = Meteor.users.find({_id: {$in: userIds}}).fetch();

<强>更新

从您的评论中未获得客户端上的所有用户,是否存在您实际发布用户的位置?我认为那是你失踪的部分。

您可以从发布中返回多个游标,例如

Meteor.publish('groups', function () {
    let groupsCursor = Groups.find({
        users: {
            $elemMatch: { $eq: this.userId }
        }
    });

    // find these from... ???
    let userIds = [];

    let usersCursor = Meteor.users.find({_id: {$in: userIds}});

    return [groupsCursor, usersCursor];
});

答案 1 :(得分:1)

如果您要查找整个集合中的所有用户,可以尝试以下聚合。

初始阶段会在每个文档中找到所有匹配的$group,然后是db.collection.aggregate([{ $project: { userIds: { $setIntersection: ["$userIds", [1, 2, 3]] } } }, { $unwinds: "$userIds" }, { $group: { $id: null, userIds: { $addToSet: "$userIds" } } }]) ,以便在整个集合中获取不同的用户。

<script type="text/javascript">
    $(window).scroll(function(){
        if ($(window).scrollTop() >= $('#head').height()) {
             $("#menu").css('position', 'fixed');
             alert("I'm working fine.");
        }
    });
</script>
相关问题