Chris Paterson
Chris Paterson

Reputation: 1149

How do I insert an element into an existing document?

I have an existing document that contains a nested array of elements (I'm not exactly sure of the terminology here). I have no problem creating the document. The problem arises when I need to insert a new element into the existing document. The code below may clarify what I'm trying to do:

Controller:

var Post = require('./models/post');

app.post('/post/:id/comment', function(req, res) {
    var updateData = {
        comments.comment: req.body.comment
        comments.name: req.body.name,
    };
    Post.update({_id: req.params.id},updateData, function(err,affected) {
        console.log('affected rows %d', affected);
    });
});

Model:

var mongoose = require('mongoose');

var postSchema = mongoose.Schema({
    post : String,
    name : String,
    created : {
        type: Date,
        default: Date.now
    },
    comments : [{
        comment : String,
        name : String,
        created : {
            type: Date,
            default: Date.now
        } 
    }]
});

module.exports = mongoose.model('Posts', postSchema);

So, each post can contain multiple comments. I'm just not sure how to insert a new comment into an existing post.

Upvotes: 0

Views: 85

Answers (2)

Đức Nguyễn
Đức Nguyễn

Reputation: 626

You can convert the object returned from mongodb in to an js object, and push new comment into the comments array. See the following:

var postSchema = require('./postSchema'); // your postSchema model file

postSchema.findOne({name: 'name-of-the-post'}, function (err, doc) { //find the post base on post name or whatever criteria

  if (err)
    console.log(err);
  else {
    if (!doc) { //if not found, create new post and insert into db

        var obj = new postSchema({
                  post: '...'
                  name: '...'
                  ...
                });

        obj.save(function (err) {
           if (err)
              console.log(err);
        });

    } else {
      // if found, convert the post into an object, delete the _id field, and add new comment to this post
      var obj = doc.toObject();
      delete obj._id;

      obj.comments.push(req.body.comment); // push new comment to comments array

      postSchema.update(
         {
           '_id': doc._id
         }, obj, {upsert: true}, function (err) { // upsert: true
             if (err)
                console.log(err);
         });
    }
    console.log('Done');
  }
});

Upvotes: 0

Andrei Beziazychnyi
Andrei Beziazychnyi

Reputation: 2917

Since comments is declared as array, try to use

Post.update({_id:yourid}, { $push : { comments: { comment: '', name: '' } } }, ...

Upvotes: 2

Related Questions