[英]select collection and get the last item of each in other collection in MongoDB
我使用以下代碼訂閱了該出版物。 所以在我的服務器端文件中
Meteor.publish('people', function() {
cursor = EmailDB.find({category:{$ne:"Spammer"}},{sort:{"lastMessage.date": -1},limit:20});
let transformData = (fields) => {
// this is the person we're processing now
let eadd = fields.eadd;
// get the latest message for this person
key.eadd = eadd;
let lastMessage = MessageDB.findOne(key,
{
sort: {date: -1}
}
);
// add his last message to the returned data
fields.lastMessage = lastMessage;
return fields;
};
let handle = cursor.observeChanges({
added: (id, fields) => {
fields = transformData(fields);
this.added('emails', id, fields);
},
changed: (id, fields) => {
fields = transformData(fields);
this.changed('emails', id, fields);
},
removed: (id) => {
this.removed('emails', id);
}
});
this.ready();
this.onStop(() => {
handle.stop();
});
return cursor;
}
它獲取Person的所有記錄。 我想獲取每個人的最新消息。 所以我使用了上面的代碼,但是它不起作用,它沒有向我的查詢中添加其他字段。
我只需要訂閱並獲取所有記錄,並且在每個記錄中必須有最后一條消息。
每當您想要從2個這樣的已發布集合中合並數據時,都可以選擇在客戶端或服務器上進行處理。 如果您在客戶端上執行此操作,則說明您已經為自己創建了一個競爭條件。 它可以解決,但是我發現它在服務器上更干凈,更容易。 由於您只需要訂閱一個集合,因此它在客戶端上變得非常簡單。
因此,要在服務器上進行操作,可以在發布中進行處理。 在這里,您可以轉換返回的集合(PersonDB)並向其中添加數據(MessagesDB)。
我不知道您的收藏集是什么樣的,或者它們的命名方式,所以我顯然在這里做一些假設。
Meteor.publish('people', function() {
let cursor = PersonDB.find({});
let transformData = (fields) => {
// this is the person we're processing now
let personId = fields.personId;
// get the latest message for this person
let lastMessage = MessagesDB.findOne({personId: personId},
{
sort: {createdAt: -1}
}
);
// add his last message to the returned data
fields.lastMessage = lastMessage;
return fields;
};
let handle = cursor.observeChanges({
added: (id, fields) => {
fields = transformData(fields);
this.added('personsdb', id, fields);
},
changed: (id, fields) => {
fields = transformData(fields);
this.changed('personsdb', id, fields);
},
removed: (id) => {
this.removed('personsdb', id);
}
});
this.ready();
this.onStop(() => {
handle.stop();
});
});
在客戶端上,您可以像平常一樣訂閱PersonDB,並像平常一樣進行查找,現在在每個記錄上都將附加一個“ lastMessage”字段。
您需要在MessagesDB中添加PersonDB ID(如果不是這種情況)
MessagesDB.find({PersonDB:PersonDB._id},{limit:1}).fetch()[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.