Meteor Mongo 访问 Meteor.publish 另一个集合中的 ID 列表



除了我的 Meteor.users 集合之外,我还有 RoomsMessages 集合。

作为房间架构的一部分,有一个 userId(字符串):它引用启动房间的 Meteor.userMeteor.用户只能访问他们开始的房间。

作为消息架构的一部分,有一个userId(字符串)和roomId(字符串):它们是发布消息的Meteor.user和发布消息的房间

现在,我只希望我的Meteor.用户能够订阅已发布到他们有权访问的房间的消息。因此,这包括其他用户发往他们房间的消息。下面的代码只订阅用户的消息,而不是所有的消息到他们的房间。

我将如何做到这一点?

Meteor.publish("messages", function() {
  return Messages.find({userId: this.userId});
});
我相信

你的意思是你想从当前用户启动的任何房间检索所有消息。 我认为这应该可以解决它:

Meteor.publish("messages.allForCurrentUser", function() {
    var currentUser = this.userId;
    var roomsForCurrentUser = Rooms.find({ userId: currentUser }).fetch().map(function(room) { 
        return room._id;
    });  // Gets an array of all Room IDs for the user.
    return Messages.find({ roomId: { $in: roomsForCurrentUser } });
});

我首先抓取当前用户,然后使用它来查找用户启动的所有房间。 接下来,.map 允许我从对象数组 [{ _id: 'blah'}, ...] 转换为字符串内部 id 数组 ['blah', ...]。 然后,我使用 MongoDB $in 来获取该房间 ID 数组中具有房间 ID 的所有消息。 我没有对用户 ID 做任何事情,因为看起来房间中的消息可能来自任何用户 ID。

最新更新