0

我的对象就像,

{
   "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>

节点:

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 及其各自的详细信息。

我如何使用nodejsand来实现这一点jade

更新:

假设有 20 个团队,我的收藏将包含 20 个文档。我想要做的是,循环浏览我的收藏并在上面描述的 20 个文档中显示信息。

  • 我的数据库结构正确吗?我应该为每个团队准备不同的文件吗?

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

4

2 回答 2

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

那会给你数据。

于 2013-01-28T11:06:14.127 回答
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"
于 2013-02-03T17:21:06.710 回答