在Nodejs中将值推入Mongodb模型

您好我正在使用MEAN stack与两个相互关联的数据模型:

发表和评论

所以在我的PostSchema

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

并在我的CommentSchema

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

在我的视图中input注释之后,我希望后端将注释保存在Comment集合中,并将注释保存在Post集合中。

在我的服务器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]。 我search了networking,但无法find任何类似的使用push例子。

你能不能让我知道我是否被误导了,如果有另一种方式我应该这样做?

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

看起来你没有定义ARRAY的评论,但只有一个(标准)的评论,因此它不是数组,它没有“推”的方法。 定义应该如下所示:

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