2016-03-29 91 views
0

我有兩個集合:CommandsCommandHistory。我正在嘗試製作一個輸出結果,其中包含兩個結果,加起來就是CommandHistory之間的任何內容都是粗體。也就是說,這東西看起來像:在模板助手中連接兩個查詢的結果

**Do the thing** <--| **Command History* 
Doing thing   <-| 
thing is in progress <-| Commands 
thing is done   <-| 
**Do the other thing**    <-| **Command History** 
I don't know what the other thing is <-| Commands 

這裏是一個輔助的基本開始:

log() { 
    const commandCursor = Commands.find({}, { sort: { timestamp: 1 } }); 
    const commandHistory = CommandHistory.find({}, { sort: { timestamp: 1 } }); 
    // what now? Need to concatenate them. 
    // `.fetch()` makes the interface seem non-reactive. 
} 

我真的可以想到的唯一的事情就是讓另一個(null)採集和輸出一切從兩個集合到它,這似乎是矯枉過正。

是否可以將這兩個遊標的結果連接起來,並且仍然使其處於被動狀態?

+0

是否有一個將'Commands'與'CommandHistory'聯繫起來的密鑰?看起來後者中每一個都有幾個前者。 –

+0

CommandHistory被添加到他們提交表單幷包含該表單的值時。成功提交後,它通過Meteor方法運行命令 – corvid

+0

因此,兩個集合之間有一個關鍵關係? –

回答

1

我認爲你要找的主要是一種方法來結合兩個結果集。 對於這一點,你可以使用這樣的事情:

log: function() { 
     var commands = Commands.find({}, { sort: { timestamp: 1 } }).map(function(i){i.origin='command'; return i;}); 
     var history = History.find({}, { sort: { timestamp: 1} }).map(function(i){i.origin='history'; return i;}); 
     var combined = _.union(commands, history); 
     return _.sortBy(combined, function(i) { return Number(i.timestamp) }); 
    } 

這裏我加入了一個名爲「出身」,以確定其中每個條目從來到現場。此外,我正在對基於時間戳的組合數據集進行排序,我正在考慮簡化數字以簡化示例。

一旦數據集相結合,您可以使用其他的幫手,其中有或無**返回,這取決於產地打印出來:

output: function(obj) { 
    var text = obj.value || ""; 
    if(obj.origin == 'history') text = "**"+text+"**"; 
    return text 
} 

下面是一個示例代碼,你可以嘗試:

HTML: 你好

<body> 
    {{> hello}} 
</body> 

<template name="hello"> 
    <ul> 
    {{#each log}} 
     <li>{{output this}}</li> 
    {{/each}} 
    </ul> 
</template> 

JS:

Commands = new Mongo.Collection("commands"); 
History = new Mongo.Collection("history"); 

if (Meteor.isClient) { 
    // counter starts at 0 
    Session.setDefault('counter', 0); 

    Template.hello.helpers({ 
    log: function() { 
     var commands = Commands.find({}, { sort: { timestamp: 1 } }).map(function(i){i.origin='command'; return i;}); 
     var history = History.find({}, { sort: { timestamp: 1} }).map(function(i){i.origin='history'; return i;}); 
     var combined = _.union(commands, history); 
     return _.sortBy(combined, function(i) { return Number(i.timestamp) }); 
    }, 

    output: function(obj) { 
     var text = obj.value || ""; 
     if(obj.origin == 'history') text = "**"+text+"**"; 
     return text 
    } 
    }); 

} 

if (Meteor.isServer) { 
    Meteor.startup(function() { 
    Commands.remove({}); 
    History.remove({}); 
    for (var i=1; i<5; i++) { 
     History.insert({value: 'history '+i, timestamp: 10*i}); 
     for (var j=1; j<4; j++) 
     Commands.insert({value: 'command '+i+'.'+j, timestamp: 10*i+j}); 
    } 
    }); 
} 
相關問題