【问题标题】:Pushing values into Mongodb model in Nodejs在 Nodejs 中将值推送到 Mongodb 模型中
【发布时间】:2016-10-29 02:10:05
【问题描述】:

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

发布和评论

所以在我的PostSchema 我有

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

在我的CommentSchema 我有

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

在我的视图中输入评论后,我希望后端将评论保存在 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]。我在网上搜索但找不到任何类似的push 正在使用的例子。

如果我被 push 误导了,请告诉我,如果我有其他方法可以这样做?

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

【问题讨论】:

  • 这个错误意味着post.comments不是一个数组。

标签: node.js mongodb mongodb-query mean


【解决方案1】:

看起来您没有定义 cmets 的 ARRAY,但只有一个(标准)注释,因此它不是数组,也没有“push”方法。定义应如下所示:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-21
    • 2020-04-17
    • 1970-01-01
    • 2016-11-17
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多