Steven Chen
Steven Chen

Reputation: 387

How to add a new object to an array in Mongoose?

I keep getting the following error when I push a new comment document into a story collection in 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\')}' 
}

This is my model:

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 }
});

This is my query:

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);
        });
    })
});

I've tried Googling the solution but still can't fix the error.

Edit:

The collection that I want to add to currently looks like this:

> 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
}

Upvotes: 2

Views: 3584

Answers (2)

deepakchauhan
deepakchauhan

Reputation: 290

You should have inserted the first entry in "comments' field wrong. As this is an array you must push the object in comment array . It seems you directly assigned the comment object to "comments" field while inserting first comment. Please check the same and it will be reolved

Upvotes: 0

Erin Recachinas
Erin Recachinas

Reputation: 115

Instead of using findOne, try using findOneAndUpdate with the $addToSet operator (http://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate).

It would look something like:

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

Upvotes: 3

Related Questions