如何将元素插入现有文档?

时间:2014-05-31 17:20:38

标签: node.js mongoose

我有一个包含嵌套元素数组的现有文档(我不完全确定这里的术语)。我创建文档没有问题。当我需要在现有文档中插入新元素时,就会出现问题。下面的代码可能会澄清我尝试做的事情:

控制器:

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

型号:

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

因此,每个帖子都可以包含多个评论。我只是不确定如何在现有帖子中插入新评论。

2 个答案:

答案 0 :(得分:2)

由于注释被声明为数组,请尝试使用

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

答案 1 :(得分:0)

您可以将从mongodb返回的对象转换为js对象,并将新注释推送到comments数组中。请参阅以下内容:

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