Meteor从userId获取用户名,更简单的方法

shm*_*mck 4 meteor meteor-accounts

使用流星:

我在Messages中有一个消息列表,用于存储userId.

Messages = new Mongo.Collection('messages'); 

// example of message data:

{
authorId: 'XFdsafddfs1sfd', // corresponding to a Meteor.userId
content: 'some Message'
}
Run Code Online (Sandbox Code Playgroud)

我正在发布消息和现有用户.

Meteor.publish('messages', function () {
  return Messages.find({});
});

Meteor.publish('users', function () {
  return Meteor.users.find({});
});
Run Code Online (Sandbox Code Playgroud)

目前,我可以获取消息列表并根据userIds添加用户名.由于用户可以更改其用户名和配置文件信息,因此将用户数据添加到集合中只是userIds是没有意义的.

var messages = Messages.find({}).fetch();
var messages.forEach(function(message) {
    message.username = Meteor.users.find(message.authorId).fetch() [0].username; // ugly
  });
Run Code Online (Sandbox Code Playgroud)

此代码有效,但涉及大量浪费的调用.我想知道如何以更好的方式实现这一目标.

在Meteor中,将用户数据与包含userIds的集合配对的最有效和最干净的方法是什么?

Sbl*_*Sbl 6

这是一个常见的用例:在db中存储其他集合的id,并在UI上使用人类可读的参数.

在Meteor中,collection.find()函数提供了传递此用例的转换回调.

var cursor = messages.find(
    {},
    {   
        transform: transformMessage
    }
);
Run Code Online (Sandbox Code Playgroud)

转换函数现在可以直接修改你的对象,添加/修改/删除你所获取对象的属性(注意:出于安全原因,不要在客户端修改/删除:改为在服务器端使用过滤器并允许/拒绝) .

function transformMessage(message) {
    var user = Meteor.users.findOne(message.authorId);
    if (user) {
        var username = user.username;
        message.username = username;
    }
    return message;
};
Run Code Online (Sandbox Code Playgroud)

这种方式的好处是:您仍在使用游标并阻止fetch().当然,代码更清晰.