Thinkerer
Thinkerer

Reputation: 1626

Filtering user Ids from an array of users

I wish to find all users, not the current User. A pair of users are stored within a "Room" array under this collection structure:

structure of each room (from another html page)

var newRoom = Rooms.insert({
   owner    : Meteor.userId(),
   receiver : receiver,
   people   : [ owner , receiver ],
}); 

Collection.js (using dburles collection helper)

Rooms.helpers({
  receiverName: function() {  
    return Meteor.users.findOne({ _id: this.receiver }).username; 
  }
});

html

<!-- **allRooms.html** Works fine, names appear --> 
  {{#each rooms}} {{receiverName}}{{/each }}

<!-- **roomDetail.html**  names dont show, this.receiver undefined --> 
    {{receiverName}} 

roomDetail js template helper

self.subscribe('room', Router.current().params._id);
self.subscribe('users');
});  

How do I return and display the user's Id thats not the current user from the people field which is an array? I hope to show it in the child page (roomDetail).

Upvotes: 0

Views: 114

Answers (1)

David Weldon
David Weldon

Reputation: 64312

Assuming:

  • Rooms is a collection, and you already have a room document to search on.
  • You only want to fetch a single user.

Give this a try:

// The list of userIds in room minus the current user's id.
var userIds = _.without(room.People, Meteor.userId());

// Assuming we want only one user...
var user = Meteor.users.findOne({ _id: userIds[0] });

Some thoughts about your original code:

  • You can't include references to Rooms in your Meteor.users selector unless Rooms is a field of users. Mongo has no notion of joins.
  • $ne isn't that you want. If you had 100 users published, and your array only contained 2 users (one of which you didn't want), using $ne would return 99 users.

Based on your comments, it looks like you need this in a collection helper. Maybe something like this:

Rooms.helpers({
  findUser: function() {
    var userIds = _.without(this.People, Meteor.userId());
    return Meteor.users.findOne({ _id: userIds[0] });
  },
});

And then elsewhere in your code, for a given room instance you could do:

room.findUser()

Upvotes: 1

Related Questions