获取MongoDB的嵌入式收集文档

问题描述:

鉴于这种DB馆藏结构:获取MongoDB的嵌入式收集文档

{ 
     "_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" 
       } 
     ] 
} 

我可以得到所有的 “标签” 集合是这样的:

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

然后:

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

但是我怎样才能列出每个tabfeeds的每个元素tab

所以你需要做的是在你的$.each调用中创建的匿名函数中创建一个参数。这将是您在数组中的当前项目的索引。然后,您将使用该索引获取与该索引对应的数据,该数组名为data

然后,您将查看您正在使用的对象并获取tabfeeds属性,该属性将为数组。然后你循环访问每个标签对象的tabfeeds数组,并对该数据做任何你想做的事情。

// 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 + "'>"; 
    }); 

});