
Question:
Right now I have a working messaging system developed in Meteor where users can send private messages to each other.
The server looks like this:
// .. 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
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" }
How can I change the object to return the username instead of the user id?
Answer1: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;
};
<strong>Edit:</strong>
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.
If in your app you allow users to change username
, it might be a good idea to <em>also</em> keep the _id
for the record.
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).
I suggest adding the collection helpers package from atmosphere. Then create a helper for PMs called toUser that returns the appropriate user. Then you can get the name using message.user.name.