2017-05-16 24 views
0

這應該是一個簡單的流星多對多關係,但我必須錯過一些東西,因爲我無法讓它工作。如何匹配一個集合中的整數與另一個集合中的整數相同,從而創建多對多關係。

我有一個名爲收集一個reblog並在它被稱爲descovered看到圖像

enter image description here

我有一個名爲帖子第二收集這是帖子的集合整數數組,並這些帖子有一個ID。看看第二圖像

enter image description here

我想創建一個多到職位一個reblog集合之間的多對多關係。即,我想整

descovered: 9

從一個reblog集合匹配,具有:

id: 9

帖子集合,這樣我可以只顯示從匹配的職位reblog集合。這當然會讓我顯示帖子的標題和其他屬性。

這是我的js

Template.reblogging.helpers({ 
descovered() { 
    var id = FlowRouter.getParam('_id'); 

    //fetch the reblog collection contents 

    var rebloged = reblog.find().fetch(); 

    //log below is showing that the fetch is successful because i can see the objects fetched in console 

    console.log(rebloged); 

    //create the relationship between the posts collection and the reblog collection 

    var reblogger = posts.find({ 
    id: { 
     $in: rebloged 
    } 
    }).fetch(); 

    //nothing is showing with the log below, so something is going wrong with the line above? 

    console.log(reblogger); 
    return reblogger 
} 
}); 

我必須失去了一些東西,因爲這似乎是一個非常簡單的事情,但它不是迴環

而我的HTML是這樣

<template name="reblogging"> 
{{#each descovered }} 
<ul class=""> 
    <li> 
    <h5 class="">{{title.rendered}}</h5> 
    </li> 
</ul> 
{{/each}} 
</template> 

回答

0

因爲它結果表明,匹配是準確的,但是,來自reblog集合的數據需要用REGEX處理以除掉除val以外的所有其他數據我需要的,然後把他們變成一個數組,這是最終的代碼工作。把它留在這裏,希望它能幫助未來的人。

Template.reblogging.helpers({ 
descovered() { 
    var id = FlowRouter.getParam('_id'); 

    //fetch the reblog collection contents 

    var rebloged = reblog.find().fetch(); 

    //log below is showing that the fetch is successful because i can see the objects fetched in console 

    console.log(rebloged); 

    //turn it into a string so i can extract only the ids 
    var reblogString = JSON.stringify(rebloged).replace(/"(.*?)"/g, '').replace(/:/g, '').replace(/{/g, '').replace(/}/g, '').replace(/,,/g, ',').replace(/^\[,+/g, '').replace(/\]+$/g, ''); 
    //after have extracted what i needed, i make it into an array 
    var reblogArr = reblogString.split(',').map(function(item) { 
    return parseInt(item, 10); 
    }); 

    //create the relationship between the posts collection and the reblog collection 

    var reblogger = posts.find({ 
    id: { 
     $in: reblogArr 
    } 
    }).fetch(); 

    //nothing is showing with the log below, so something is going wrong with the line above? 

    console.log(reblogger); 
    return reblogger 
} 
}); 
1

你並不需要轉換爲字符串和解析,就可以直接使用.map()上的光標創建descovered值的數組。此外,因爲您正在使用Blaze,您可以返回一個遊標而不是數組。我懷疑你也打算在你的第一個.find()中使用你的FlowRouter _id參數。如果你沒有,那麼就沒有必要在你的幫手中得到這個參數。

Template.reblogging.helpers({ 
    descovered() { 
    const id = FlowRouter.getParam('_id'); 
    const reblogArr = reblog.find(id).map(el => { return el.descovered });  
    return posts.find({ id: { $in: reblogArr } }); 
    } 
); 
+0

我不能得到這個工作。 ** console.log(reblogArr); **不顯示任何內容,@Michel –

+0

什麼是'reblog.find(id).count()'? –

相關問題