2013-10-20 68 views
0

我現在有一個數據庫(貓鼬),其模式被定義爲閱讀數元素:玉不是從JSON對象

var CommentTableSchema = new mongoose.Schema({ 

    name: String, 
    body: String, 
    parentCommentID: String, 
    depth: Number, // the depth of the comment to which it is nested. 
}); 
CommentTableSchema.set('collection', 'comment'); 

我保存在我的數據庫中的新評論做:

var comment = mongoose.model('comment', CommentTableSchema); 
     var currentComment = new comment({name: request.body.name, body: request.body.comment, parentCommentID: "" , depth: 1}); 
     currentComment.save(function (err, currentComment) { 
      if (err) { 
       console.log("saving error : " + currentComment); 
      } 
      else { 
       console.log("saved!"); 
      } 
     }); 

我將comment.find的結果傳遞給我的home.jade文件。在玉文件我有以下行(commentsTable是comment.find結果)

-each comment in commentsTable 
    div 
     -console.log("comment depth: " + comment.depth) 
     if comment.hasOwnProperty('depth') 
      |has depth 
     else 
      |no depth 

這個輸出「沒有深度」我的瀏覽器頁面上。然而行-console.log("comment depth: " + comment.depth)給我我的終端上輸出如下:

comment depth: 1 
comment depth: 1 
comment depth: 1 

預計。爲什麼玉不能看我的depth會員?我在訪問我的home.jade文件中的comment.namecomment.bodycomment._id時沒有問題。

+0

我找到了解決方法。我沒有做'comment.depth',而是評論['depth']'這似乎給了我想要的價值。我不明白爲什麼會發生這種情況考慮'comment.name'和'comment.id'給了我沒有問題。我要離開這個問題,希望有人能夠弄清楚什麼是錯的。 –

回答

1

在此回調

currentComment.save(function (err, currentComment)

currentComment是貓鼬文檔對象

這聽起來像你想要的是平淡的結果,而不是貓鼬裹結果

我d建議您在將對象傳遞到模型之前調用Document#toObject([options])這裏引用的函數http://mongoosejs.com/docs/api.html#document_Document-toObject

沿着類似的方向,您應該在執行查找操作時查看選項lean。指定時,mongoose返回未包裝的對象。

ex:http://mongoosejs.com/docs/api.html#model_Model.findById