如何在Mongoose中向数组添加新对象?

时间:2015-08-17 21:15:16

标签: javascript node.js mongodb mongoose nosql

当我将新的评论文档推送到Mongoose的故事集中时,我一直收到以下错误:

{ 
[MongoError: The field 'comments' must be an array but is of type Object in document {_id: ObjectId('55d2429477da83b6f593ce53')}]
  name: 'MongoError',
  message: 'The field \'comments\' must be an array but is of type Object in document {_id: ObjectId(\'55d2429477da83b6f593ce53\')}',
  driver: true,
  index: 0,
  code: 16837,
  errmsg: 'The field \'comments\' must be an array but is of type Object in document {_id: ObjectId(\'55d2429477da83b6f593ce53\')}' 
}

这是我的模特:

var commentSchema = new Schema({
    text: String,
    date: { type: Date, default: Date.now },
    author: String  
})
var storySchema = new Schema({
    title: String,
    link: String,
    comments: [commentSchema],
    author: String,
    date: { type: Date, default: Date.now }
});

这是我的疑问:

app.post('/news/:id/comment', function(req, res) {
    console.log('Hi Received');
    var comment = {
        "author": 'Steven',
        "text": req.body.comment
    }
    Story.findOne({_id: req.params.id}, function(err, data) {
        if(err) throw err;
        data.comments.push(comment);
        data.save(function(err, data){
            if (err) console.log(err);
            console.log(data);
        });
    })
});

我尝试使用谷歌搜索解决方案,但仍然无法解决错误。

编辑:

我想要添加的集合目前看起来像这样:

> db.stories.find().pretty()
{
    "_id" : ObjectId("55d2429477da83b6f593ce53"),
    "author" : "Steven Chen",
    "link" : "AS",
    "title" : "AS",
    "date" : ISODate("2015-08-17T20:22:44.271Z"),
    "comments" : {
         "author" : "Steven",
         "text" : "Alsawdksada"
    },
    "__v" : 0
}

2 个答案:

答案 0 :(得分:3)

请尝试将findOnefindOneAndUpdate运算符(http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate)一起使用,而不要使用$addToSet

看起来像是:

Story.findOneAndUpdate(
    {_id: req.params.id}, 
    {$addToSet: {comments: comment}}, 
    function(err,data) { 
       if(err) throw err; 
    }
)

答案 1 :(得分:0)

您应该在“评论”字段中插入错误的第一个条目。 由于这是一个数组,您必须在注释数组中推送对象。在插入第一条评论时,您似乎直接将评论对象分配给“评论”字段。 请检查一下,它将被解决