mongoose修改多级子文件,然后保存不正常工作

mongoose修改多级子文件,然后保存不正常工作

问题描述:

我有一个Torrent项目,它有子文档数组命名为'_replies'保存的用户评论,并且每个评论还包括保存的用户回复的子文档数组'_replies',这是我的所有架构定义:mongoose修改多级子文件,然后保存不正常工作

var CommentSchema = new Schema({ 
    user: { 
    type: Schema.Types.ObjectId, 
    ref: 'User' 
    }, 
    comment: { 
    type: String, 
    default: '', 
    trim: true 
    }, 
    _replies: [this], 
    createdat: { 
    type: Date, 
    default: Date.now 
    }, 
    editedby: { 
    type: String, 
    default: '', 
    trim: true 
    }, 
    editedat: { 
    type: Date, 
    default: '' 
    } 
}); 

var TorrentSchema = new Schema({ 
    user: { 
    type: Schema.Types.ObjectId, 
    ref: 'User' 
    }, 
    torrent_filename: { 
    type: String, 
    default: '', 
    trim: true, 
    required: 'filename cannot be blank' 
    }, 
    torrent_title: { 
    type: String, 
    default: '', 
    trim: true, 
    required: 'title cannot be blank' 
    }, 
    _replies: [CommentSchema] 
}); 

mongoose.model('Torrent', TorrentSchema); 
mongoose.model('Comment', CommentSchema); 

洪流更新一级评论/删除精细,服务器控制器的代码如下喜欢:

exports.update = function (req, res) { 
    var torrent = req.torrent; 

    torrent._replies.forEach(function (r) { 
    if (r._id.equals(req.params.commentId)) { 
     r.comment = req.body.comment; 
     r.editedat = Date.now(); 
     r.editedby = req.user.displayName; 

     torrent.save(function (err) { 
     if (err) { 
      return res.status(422).send({ 
      message: errorHandler.getErrorMessage(err) 
      }); 
     } else { 
      res.json(torrent); //return data is Correct, and save to mongo is Correct 
     } 
     }); 
    } 
    }); 
}; 

但是当我用相同方式的功能更新/删除_replies._replies ,它可以返回正确的洪流JSON响应,联合国幸运的是,保存到蒙戈不精,代码:

exports.SubUpdate = function (req, res) { 
    var torrent = req.torrent; 

    torrent._replies.forEach(function (r) { 
    if (r._id.equals(req.params.commentId)) { 
     r._replies.forEach(function (s) { 
     if (s._id.equals(req.params.subCommentId)) { 
      s.comment = req.body.comment; 
      s.editedat = Date.now(); 
      s.editedby = req.user.displayName; 

      torrent.save(function (err) { 
      if (err) { 
       return res.status(422).send({ 
       message: errorHandler.getErrorMessage(err) 
       }); 
      } else { 
       res.json(torrent);//return data is Correct, but save to mongo is incorrect 
      } 
      }); 
     } 
     }); 
    } 
    }); 
}; 

另外,我可以删除第一级评论,但不能删除第二个层次评论回复,洪流的所有JSON数据是正确的,不仅没有节省蒙戈。

我能做些什么?

我已经解决了它,我在.save()之前添加了这段代码。

torrent.markModified('_replies'); 

它工作正常!