【问题标题】:How to add a new object to an array in Mongoose?如何在 Mongoose 的数组中添加新对象?
【发布时间】:2015-11-10 15:31:50
【问题描述】:

当我将新评论文档推送到 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
}

【问题讨论】:

  • 您的收藏文档与您的架构不匹配。正如错误消息所说,comments 是一个对象,而不是一个数组。

标签: javascript node.js mongodb mongoose nosql


【解决方案1】:

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

它看起来像:

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

【讨论】:

  • 试过了,仍然返回类似的错误:MongoError: exception: Cannot apply $addToSet to a non-array field. Field named 'comments' has a non-array type Object in the document _id: ObjectId('55d2429477da83b6f593ce53')
  • 更新后 - 您的 cmets 架构看起来像是单个对象而不是列表。尝试在 { "author" : "Steven", "text" : "Alsawdksada" } 周围添加另一组花括号
  • 我更新了当前集合在 Mongo 中的样子
  • 我想我知道问题出在哪里。这可能与我最初插入数据的方式有关。我就是这样做的:for (var x = 0; x < Object.keys(req.body).length; x++) { story['title'] = req.body['title']; story['link'] = req.body['link']; story['comments'].text = req.body['comments']; story['comments'].author = 'Steven'; story['author'] = 'Steven Chen';
  • 是的!尝试从空 cmets 开始,然后使用您的 post 方法,一切都应该没问题。
【解决方案2】:

您应该错误地在“cmets”字段中插入了第一个条目。 由于这是一个数组,您必须将对象推送到评论数组中。似乎您在插入第一条评论时直接将评论对象分配给“cmets”字段。 请检查相同,它会得到解决

【讨论】:

    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 2019-04-23
    • 2019-02-13
    • 2021-09-01
    • 2015-06-16
    • 2016-05-21
    • 2022-01-07
    • 2012-11-16
    相关资源
    最近更新 更多