2013-05-13 54 views
0

目前我看到的所有內容都顯示整個文檔,而不僅僅是一個字段。我將如何顯示一個字段?如何使用Mongoose和Jade在Nodejs上顯示Mongo字段?

我試過以下,但我得到「未定義」s,我沒有看到任何顯示。

方式1主要的js:

// app.js 

var schema = new mongoose.Schema({ a_field : String }, 
           { collection : 'the_col_with_data' }); 
var DocumentModel = mongoose.model('Doc', schema); 
var a_document = DocumentModel.findOne({}, callback); 

app.get('/', function(req, res) { 
    res.render('index', { 
          pass_var: a_document.a_field 
         }); 
}); 

方式1個圖:

// index.jade 

#{ pass_var } 

方式2個主要JS:

// app.js 

var schema = new mongoose.Schema({ a_field : String }, 
           { collection : 'the_col_with_data' }); 
var DocumentModel = mongoose.model('Doc', schema); 
var a_document = DocumentModel.findOne({}, callback); 

app.get('/', function(req, res) { 
    res.render('index', { 
          pass_var: a_document 
         }); 
}); 

方式2圖:

// index.jade 

#{ pass_var.a_field } 

回答

1

與貓鼬的交互是異步的。這意味着,你不能依賴貓鼬操作的返回值。您必須在回調中執行對文檔進行操作的邏輯。所以在你的情況下,a_document並不指向你正在尋找的文件。相反,你必須在你的回調中使用該文件:

app.get('/', function(req, res) { 
    DocumentModel.findOne({}, function(err, doc) { 
     if(err) { 
      res.send(500); 
      return; 
     } 
     res.render('index', {pass_var: doc}); 
    }); 
}); 
+0

非常感謝NilsH!後續問題,因爲我是新的Node.js:在你的代碼'res.render()'是在二級回調。這是否意味着回調可以有很多級別,並且它們只是遞歸地向外返回到父回調?你知道我在哪裏可以閱讀更多關於這個? – 2013-05-13 06:18:32

+0

是的,你經常有幾個級別的回調。所以爲了使它更具可讀性,我建議你看一看存在的許多「流」庫,例如['async'](https://github.com/caolan/async/),['step' ](https://github.com/creationix/step)或['seq'](https://github.com/substack/node-seq),或者他們都叫什麼。 – NilsH 2013-05-13 07:06:20

相關問題