鉴于此数据库集合结构:
{
"_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
的每个元素?
最佳答案
因此,您需要做的是在 $.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/