node.js - 获取 MongoDB 嵌入式集合文档

标签 node.js express mongodb-query

鉴于此数据库集合结构:

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

但是如何列出每个 tabtabfeeds 的每个元素?

最佳答案

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

});

关于node.js - 获取 MongoDB 嵌入式集合文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46221760/

相关文章:

mongodb - 获取数组 mongodb 中的特定字段并作为数组返回

mysql - 为什么我的数据没有插入到我的数据库中

javascript - 在特定条件的嵌套级别收集不同的字段名称

javascript - 使用 for 循环为数组提供错误

node.js - gRPC Node : How to set a field that is of another Message type (with multiple types itself)

mysql - 如何在 Node/Express 中为数组的每次迭代发送 Post 请求?

javascript - 如何在 Express 的 res.redirect() 中使用变量?

python - 将 SQL 查询转换为 mongo 查询

node.js - 为什么我会收到此错误? r1= buf1.比较(buf2); ^ 类型错误 : Object Rahul has no method 'compare'

node.js - firebase-admin:获取失败通知传递结果的 token