2015-07-12 86 views
4

使用流星:流星從userId獲取用戶名,更簡單的方法

我有一個存儲userId的消息中的消息列表。

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

// example of message data: 

{ 
authorId: 'XFdsafddfs1sfd', // corresponding to a Meteor.userId 
content: 'some Message' 
} 

而我發佈消息和現有的用戶。

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

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

目前我可以抓取消息列表並添加基於userIds的用戶名。由於用戶可以更改其用戶名&配置文件信息,因此向用戶數據添加用戶數據(僅userIds)沒有任何意義。

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

此代碼有效,但涉及大量浪費的調用。我想知道如何以更好的方式實現這一點。

在流星中,什麼是最有效的&最簡潔的方式來將用戶數據與包含userIds的集合配對?

+0

您是否可以控制消息的創建方式或讀取現有的mongo數據庫? – sergserg

+1

你看過這個嗎?可能對你有意思。 https://www.discovermeteor.com/blog/reactive-joins-in-meteor/ – tomsp

+0

我有控制數據庫。 @tomsp我會看看,謝謝! – shmck

回答

6

這是一個常見用例:將其他集合的id存儲在db中,並在UI上使用人類可讀的參數。

在Meteor中,collection.find()函數提供了爲這個用例傳遞一個轉換回調。

var cursor = messages.find(
    {}, 
    { 
     transform: transformMessage 
    } 
); 

轉換功能現在可以直接修改你的對象,添加/修改/刪除您獲取對象的屬性(注意:不要修改/在客戶端刪除出於安全原因:不是在使用過濾器服務器端和允許/拒絕)。

function transformMessage(message) { 
    var user = Meteor.users.findOne(message.authorId); 
    if (user) { 
     var username = user.username; 
     message.username = username; 
    } 
    return message; 
}; 

這種方式的好處是:您仍在使用遊標並阻止fetch()。當然,更簡潔的代碼。

+0

看來剩下的問題是'Meteor.users.findOne()'是未定義的。僞用戶使用'Meteor.users.insert()'添加,並且可以在數據庫中找到用戶名。任何想法,爲什麼我不能從'Meteor.users.find()'訪問任何用戶數據? – shmck

+0

使用'transform'時,'Meteor.users'可以在服務器上訪問,但不能在共享客戶端/服務器空間中訪問。我如何轉換消息/用戶數據? – shmck

相關問題