2016-06-27 16 views
1

HI我使用的是相互關聯的MEAN stack有兩個數據模型:推值到MongoDB的模型中的NodeJS

郵政和評論

所以在我的PostSchema我有

comments:{ 
     type:mongoose.Schema.Types.ObjectId, 
     ref:'Comment' 

,並在我的CommentSchema我有

post:{ 
     type:mongoose.Schema.Types.ObjectId, 
     ref:'Post' 
    } 

After我在我的視圖中輸入評論我希望後端將評論保存在評論集合中,並將評論保存在帖子集合中。

在我的服務器app.js文件:

comment.save(function(err,comment){ 
     if(err){return next(err);} 
     var post = new Post(req.post) 
     post.comments.push(comment) 
     // OR req.post.comments.push(comment);etc 
     post.save(function(err,post){ 
      if(err){return next(err);} 

      res.json(comment); 
     }) 
    }) 

但是,當我用post.comments.pushreq.post.comments.push,我得到命令行push is not a function的錯誤消息。

上述代碼來自在線教程[1]。我搜索了網絡,但無法找到使用push的任何類似示例。

如果我被push誤導了,並且如果有另一種方法我應該這樣做,您能否讓我知道?

[1] https://thinkster.io/mean-stack-tutorial#wiring-everything-up

+0

錯誤意味着'post.comments'不是數組。 – Shrabanee

回答

1

看起來你並沒有確定的意見ARRAY,但只有一個(標準)的評論,因此不陣列,它並沒有「推」的方法。定義應該如下所示:

comments:[{ 
     type:mongoose.Schema.Types.ObjectId, 
     ref:'Comment'}] 
+0

這是現貨,謝謝! –