Mongodb查询嵌套对象

时间:2013-01-28 10:33:48

标签: node.js mongodb pug express

我的对象就像,

{
   "Team-A": {
        "captain": "A",
        "homeGround": "some ground",
        "winLoss": "12-4-0"
    },
    "Team-B": {
        "captain": "B",
        "homeGround": "some ground 2",
        "winLoss": "4-4-4"
    }
}

我需要将此信息显示为

<h1>Team-A</h1>
<h2>some ground</h2>
<h3>12-4-0</h3>

<h1>Team-B</h1>
<h2>some ground2</h2>
<h3>4-4-4</h3>

的NodeJS:

MongoClient.connect("mongodb://localhost:27017/MY_DB_TEST", function(err, db) {
      if(!err) {
        console.log("We are connected");        

        var collection =  db.collection('football_teams');      
        var stream = collection.find().stream();

        stream.on("data", function(item){
            console.log(item);
            res.render('index', {obj: item });
        });     
      }
    });

h1= obj.captain
h2= obj.homeGround
h3= obj.winLoss

我的控制台输出是:

{ _id: 51064fa1e0d5d118b4b29aa0,
  'Team-A': {
        'captain": 'A',
        'homeGround": 'some ground',
        'winLoss': '12-4-0'
    } }

title is not defined
    at eval (eval at <anonymous> (C:\node_modules\jade\lib\jade.js:176:8))
    at exports.compile (C:\node_modules\jade\lib\jade.js:181:12)
    at Object.exports.render (C:\node_modules\jade\lib\jade.js:216:14)
    at View.exports.renderFile [as engine] (C:\node_modules\jade\lib\jade.js:243:13)
    at View.render (C:\node_modules\express\lib\view.js:75:8)
    at Function.app.render (C:\node_modules\express\lib\application.js:503:10)
    at ServerResponse.res.render (C:\node_modules\express\lib\response.js:721:7)
    at CursorStream.exports.index (C:\Users\HFR&D\Desktop\nodemongoexpress\routes\index.js:18:8)
    at CursorStream.EventEmitter.emit (events.js:96:17)
    at CursorStream._onNextObject (C:\Users\HFR&D\Desktop\nodemongoexpress\node_modules\mongodb\lib\mongodb\cursorstream

我不明白我应该如何遍历我的对象并获取Team-A / Team-B的值及其各自的详细信息。

如何使用nodejsjade实现此目的。

更新

假设有20支球队,我的收藏将包含20个文件。我想要做的是,循环我的收藏并在20个文档中显示信息,如上所述。

  • 我的数据库结构是否正确?我应该为每个团队提供不同的文件吗?

  • 如果是,我如何在玉器渲染时动态获取文件的标题(团队-A,团队-B)?

2 个答案:

答案 0 :(得分:0)

您可以在console.log

中看到Team-A集合
{ _id: 51064fa1e0d5d118b4b29aa0,
  'Team-A': {
        'captain": 'A',
        'homeGround": 'some ground',
        'winLoss': '12-4-0'
    } }

你得到的错误是title is not defined,所以我猜其他东西正在破坏你的代码。 (也许没有设置布局的标题变量?)

解决问题后,确实如此

h1= obj['Team-A'].captain
h2= obj['Team-A'].homeGround
h3= obj['Team-A'].winLoss

这将为您提供数据。

答案 1 :(得分:0)

var myobj = {
 "Team-A": {
   "captain": "A",
   "homeGround": "some ground",
   "winLoss": "12-4-0"
 },
 "Team-B": {
   "captain": "B",
   "homeGround": "some ground 2",
   "winLoss": "4-4-4"
 }
};

var key = Object.keys(obj)[0] // gives you the first key i.e. Team-A. its an array so every key is easily accessible.
var captain = myobj[key].captain // gives 'A'
var homeGround = myobj[key].homeGround // gives 'some ground'
var winloss = myobj[key].winloss //gives "12-4-0"