2013-10-20 67 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