我希望找到所有用户,而不是当前用户。一对用户存储在该集合结构下的“Room”数组中:
每个房间的结构(来自另一个html页面)
var newRoom = Rooms.insert({
owner : Meteor.userId(),
receiver : receiver,
people : [ owner , receiver ],
});
Collection.js(使用 dburles 集合助手)
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 模板助手
self.subscribe('room', Router.current().params._id);
self.subscribe('users');
});
如何从数组形式的 people
字段中返回并显示不是当前用户的用户 ID?我希望在子页面(roomDetail)中显示它。
最佳答案
假设:
Rooms
是一个集合,您已有一个可供搜索的room
文档。- 您只想获取单个用户。
尝试一下:
// 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] });
关于原始代码的一些想法:
- 您不能在
Meteor.users
选择器中包含对Rooms
的引用,除非Rooms
是用户字段。 Mongo 没有连接的概念。 $ne
不是您想要的。如果您发布了 100 个用户,并且您的数组仅包含 2 个用户(其中之一是您不想要的),则使用$ne
将返回 99 个用户。
根据您的评论,您似乎需要在collection helper中使用它。也许是这样的:
Rooms.helpers({
findUser: function() {
var userIds = _.without(this.People, Meteor.userId());
return Meteor.users.findOne({ _id: userIds[0] });
},
});
然后在代码的其他地方,对于给定的 room
实例,您可以执行以下操作:
room.findUser()
关于javascript - 从用户数组中过滤用户 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36258799/