Meteor用户间的私人消息传递

Meteor用户间的私人消息传递,meteor,Meteor,现在,我有一个在Meteor中开发的工作消息系统,用户可以互相发送私人消息 服务器如下所示: // .. lot of code Meteor.publish("privateMessages", function () { return PMs.find({ to: this.userId }); }); PMs.allow({ insert: function(user, obj) { obj.from = user; obj.to = Met

现在,我有一个在Meteor中开发的工作消息系统,用户可以互相发送私人消息

服务器如下所示:

// .. lot of code
Meteor.publish("privateMessages", function () {
    return PMs.find({ to: this.userId });
});
PMs.allow({
    insert: function(user, obj) {
        obj.from = user;
        obj.to = Meteor.users.findOne({ username: obj.to })._id;
        obj.read = false;
        obj.date = new Date();
        return true;
    }
});
// .. other code
当用户订阅privateMessages时,他会得到一个如下所示的mongo对象:

{ "to" : "LStjrAzn8rzWp9kbr", "subject" : "test", "message" : "This is a test", "read" : false, "date" : ISODate("2014-07-05T13:37:20.559Z"), "from" : "sXEre4w2y55SH8Rtv", "_id" : "XBmu6DWk4q9srdCC2" }

如何更改对象以返回用户名而不是用户id?

您需要以类似于将用户名更改为_id的方式执行此操作。您可以创建一个实用函数:

var usernameById = function(_id) {
  var user = Meteor.users.findOne(_id);
  return user && user.username;
};
编辑:

如果您不想为每条消息轮询minimongo,只需在消息对象中包含username而不是_id即可。因为用户名是唯一的,所以它们就足够了

如果在你的应用程序中允许用户更改用户名,那么最好也保留_id作为记录


在我使用过的一个更大的应用程序中,我们在模型中保留了用户的_id,以创建到profile等的链接,并缓存了他的profile.name以供显示。

我建议从atmosphere添加collection helpers包。然后为PM创建一个名为toUser的助手,该助手返回相应的用户。
然后可以使用message.user.name获取名称

返回值应该是user.username,而不是&&username。我可以这样做,但它需要循环遍历所有mongodb文档,并且在有很多消息时会影响性能,例如example@Stennie实际上我认为如果user是truthy,它将返回user.username的值,不像我想象的那样是一个布尔值。我以前在代码中有一个错误。谢谢,@Stennie,谢谢你的注意。如果你想避免每次都查看用户集合,只需将用户名存储在邮件中,而不是与_id一起存储即可。