将数据推送到嵌入式数组错误nodeJS

时间:2015-12-11 19:57:23

标签: javascript node.js mongodb mongoose schema

我正在使用mongoose,并且在尝试将某些数据推送到我已经建立的文档之一的嵌入式数组中时出现错误。我的应用程序基本上就像一个论坛,用户发布主题问题,有人可以回答它,然后有人可以发表对该答案的评论。问题是,我已经设置了我的数据库,以便主题和答案在不同的模型中相互引用,但注释嵌入在答案模式中。我尝试的每种方法都会出错:

message: 'The field \'comment\' must be an array but is of type Object in document {_id: ObjectId(\'5669acad9b68142c1258b472\')}', 
driver: true, 
index: 0, 
code: 16837, 
errmsg: 'The field \'comment\' must be an array but is of type Object in document {_id: ObjectId(\'5669acad9b68142c1258b472\')}' }

或:

{ [ValidationError: Answer validation failed]
message: 'Answer validation failed',
name: 'ValidationError',
errors:
{ 'comment.1._id':
  { [CastError: Cast to ObjectID failed for value "[object Object]" at path
"_id"]
    message: 'Cast to ObjectID failed for value "[object Object]" at path "_
id"',
    name: 'CastError',
    kind: 'ObjectID',
    value: [Object],
    path: '_id',
    reason: undefined } } }

Answer.js:model

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var AnswerSchema = new Schema(
{
  _topic: {type: Schema.Types.ObjectId, ref: 'Topic'},
  _user: {type: Schema.Types.String, ref: 'User'},
  likes: Number,
  dislikes: Number,
  content: String,
  created_at: {type: Date, default: new Date},
  comment: [{
              _user: {type: Schema.Types.String, ref: 'User'},
              content: String
            }]

});

var Answer = mongoose.model('Answer', AnswerSchema);

topics.js:controller

add_comment: function(req,res)
  {
    Answer.findOne({_id: req.body.answerid}, function(err, answer)
    {      
      if(err)
      {
        console.log(err)
      }
      else
      {
        console.log(answer);
        answer.comment.push([{_user: req.body.currentUser, content: req.body.content}]);
        answer.save(function(err)
        {
          if(err)
          {
            console.log(err);
          }
          else
          {
           res.redirect('/'); 
          }
        })
      }
   })
  }

如果我只是更新数据(以替换其他注释),它将处理它没有错误,如果我使用像$ push这样的运算符我会收到相同的错误。

感谢您的帮助。

0 个答案:

没有答案