【问题标题】:mongoose modify multi level subdocument then save not work normally猫鼬修改多级子文档然后保存不能正常工作
【发布时间】:2017-09-20 14:01:49
【问题描述】:

我有一个 Torrent 项目,它有名为 '_replies' 的子文档数组来保存用户 cmets,每个评论还包括子文档数组 '_replies' 来保存用户回复,这是我的所有架构定义:

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

torrent更新/删除一级注释很好,服务器控制器代码如下:

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

但是当我使用Alike函数更新/删除_replies._replies时,它可以返回正确的torrent json响应,不幸的是,保存到mongo不好,代码:

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

另外,我可以删除一级评论,但不能删除二级评论回复,torrent的所有json数据都是正确的,只是不保存到mongo。

我还能做什么?

【问题讨论】:

    标签: node.js mongodb multi-level subdocument


    【解决方案1】:

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

    torrent.markModified('_replies');
    

    它工作正常!

    【讨论】:

      猜你喜欢
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      • 2014-09-06
      • 1970-01-01
      相关资源
      最近更新 更多