2017-09-14 1 views
0

Compte tenu de cette structure de collection DB:Get MongoDB collection embarqués docs

{ 
     "_id" : ObjectId("59ba5bf6fa12aa446c097793"), 
     "tab" : "tab1", 
     "tabfeeds" : [ 
       { 
         "url" : "//url1", 
         "limit" : 4, 
         "type" : "text" 
       }, 
       { 
         "url" : "//url2", 
         "limit" : 8, 
         "type" : "normal" 
       } 
     ] 
} 
{ 
     "_id" : ObjectId("59ba73a6fa12aa446c097794"), 
     "tab" : "tab2", 
     "tabfeeds" : [ 
       { 
         "url" : "//url5", 
         "limit" : 4, 
         "type" : "normal" 
       } 
     ] 
} 

je peux obtenir toute la collection "onglets" comme ceci:

router.get('/tabs', function(req, res) { 
    var db = req.db; 
    var collection = db.get('tabs'); 
    collection.find({},{},function(e,docs){ 
     res.json(docs); 
    }); 
}); 

Et puis:

$.getJSON('/feeds/tabs', function(data) { 
    $.each(data, function(){ 
     tablistcontent += '<th rel="' + this.tab + '">' + this.tab + '</th>'; 
    }); 
}); 

Mais comment puis-je lister chaque élément de tabfeeds pour chaque tab?

Répondre

2

Donc, ce que vous avez à faire est de créer un paramètre dans la fonction anonyme que vous créez dans votre appel $.each. Ce sera l'indice de l'article en cours dans le tableau. Ensuite, vous utiliserez cet index pour obtenir les données correspondant à cet index dans le tableau appelé data.

Ensuite, vous allez regarder dans l'objet que vous êtes et obtenir l'attribut tabfeeds, qui sera un tableau. Ensuite, vous parcourez le tableau tabfeeds pour chaque objet onglet et faites ce que vous voulez faire avec ces données.

// outside up here you'll have a variable to hold tab feed data 
// i'll call it tabfeedData for example 
var tabfeedData = ''; 

// loop through all the data 
$.each(data, function(tab) { 

    var tabfeeds = data[tab]["tabfeeds"]; // get array of tabfeeds from data variable 

    tablistcontent += '<th rel="' + this.tab + '">' + this.tab + '</th>'; 

    // loop through tabfeeds and do whatever you need to (like construct a string with attributes from the tabfeed object) 
    $.each(tabfeeds, function(tabfeed) { 
     tabfeedData += "<tr data-url='" + this.url + "'>"; 
    }); 

});