【问题标题】:Get MongoDB embedded collection docs获取 MongoDB 嵌入式集合文档
【发布时间】:2017-09-14 14:28:53
【问题描述】:

给定这个数据库集合结构:

{
        "_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>';
    });
});

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

【问题讨论】:

    标签: node.js express mongodb-query


    【解决方案1】:

    因此,您需要在 $.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 + "'>";
        });
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-13
      • 2020-12-27
      • 2011-05-15
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多