用户之间的流星私信 [英] Meteor private messaging between users
问题描述
现在我有一个在 Meteor 中开发的工作消息系统,用户可以在其中相互发送私人消息.
Right now I have a working messaging system developed in Meteor where users can send private messages to each other.
服务器看起来像这样:
// .. 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对象:
When the user subscribes to privateMessages, he gets a mongo object that looks like this:
{ "to" : "LStjrAzn8rzWp9kbr", "subject" : "test", "message" : "This is a test", "read" : false, "date" : ISODate("2014-07-05T13:37:20.559Z"), "from" : "sXEre4w2y55SH8Rtv", "_id" : "XBmu6DWk4q9srdCC2" }
如何更改对象以返回用户名而不是用户 ID?
How can I change the object to return the username instead of the user id?
推荐答案
您需要以类似于将 username
更改为 _id
的方式执行此操作.你可以创建一个效用函数:
You need to do so in a way similar to how you changed username
to _id
. You can create a utility function:
var usernameById = function(_id) {
var user = Meteor.users.findOne(_id);
return user && user.username;
};
如果您不想为每条消息轮询 minimongo,只需在消息对象中包含 username
而不是 _id
.由于 username
是唯一的,所以它们就足够了.
If you don't want to poll minimongo for each message, just include username
instead of _id
inside your message object. Since username
is unique, they will be enough.
如果在您的应用中您允许用户更改用户名
,最好也保留_id
以作为记录.
If in your app you allow users to change username
, it might be a good idea to also keep the _id
for the record.
在我使用过的一个较大的应用程序中,我们将用户的 _id
保留在模型中(以创建指向个人资料的链接等),并缓存他的 profile.name
(用于显示目的).
In one of larger apps I've been working with we kept user's _id
in the model (to create links to profile etc.), as well as cached his profile.name
(for display purposes).
这篇关于用户之间的流星私信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!