mongoose如何事物回滚
发布于 11 年前 作者 rhino 6604 次浏览 最后一次编辑是 8 年前

comment.save(function(error, comment){ BlogModel.update({_id: blogId}, { $push: { comments: comment } }, function(error, number){ if(number == 0){ comment.remove(function(error){ if(!error){ options.error({msg: ‘create comment fail: the speciall blog not exists’}) } }); }else{ DBUtil.handleQueryResult(error, comment, options); } }); 如果number等于0,此时comment实例新增成功,我还要手动将它delete,是否可以有一种方式让这个事物回滚

2 回复

为啥不反过来?

BlogModel.update({_id: blogId}, { $push: { comments: comment } }, function(error, number){
  if(number > 0){
      ....
      comment.save(function(error, comment){

是,这样也可以,我后来用了一个Middleware: commentSchema.pre(‘save’, function(next){ Blog.model.findById(this.blogId, function(error, blog){ if(error){ next(error); }else{ if(blog){ next(); }else{ var error = new Error(); error.msg = ‘create comment fail: the speciall blog not exists’; next(error); } } }); });

回到顶部