【问题标题】:MongoDB: Updating arrays of sub documents after document deletionMongoDB:删除文档后更新子文档数组
【发布时间】:2017-08-22 05:15:21
【问题描述】:

我有一个 API,我通过以下方式删除“课程”文档:

module.exports.deleteCourse = function(req, res){
  var courseid = req.params.courseid;
  if(courseid){
    Course.findByIdAndRemove(courseid, function(err, course){
      if(err){
        sendJSONResponse(res, 404, err);
        return;
      }
      sendJSONResponse(res, 204, null)
    });
  } else{
      sendJSONResponse(res, 404, {"message":"NoId"});
    }
  };

这样就成功地从数据库中删除了课程,如尝试通过 id 查找时所示。

问题是在用户文档中:

    var instructorSchema = new mongoose.Schema({
   name: {type: String,
         unique: true,
         required: true},
   password: {type: String,
            required: true},
   courses: [course.schema]
});

如果文档被推送到课程数组,它在删除方法之后仍然存在。

所以我的问题。有没有一种相对轻松的方法可以在删除后保持此文档的更新?

谢谢。

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    使用静态方法为课程添加一个类方法,您可以在其中删除课程及其依赖项。

    假设您将 id 存储在 courses 数组中:

    var Instructor = require('./instructor');
    
    courseSchema.statics = {
        removeOneWithDependencies : function(id, done){
            this.findByIdAndRemove(id, function(err, course){
                if(err){
                    return done(err);
                }
                else{
                    //Removes the course id from courses array of all instructor docs
                    Instructor.update({courses: course._id}, { $pullAll: {courses: [course._id] } }, {multi: true}, function(err){ //http://stackoverflow.com/a/27917378/
                        if(err){
                            return done(err);
                        }
                        else{
                            return done();
                        }
                    })
                }
            });
        }
    }
    

    如果您将课程文档存储在 courses 数组中,您需要将更新查询更改为:

    Instructor.update({"courses._id": course._id}, { $pull: {courses:{_id: course._id} } }, {multi: true}, function(err){ //http://stackoverflow.com/a/15122017/
    

    最后在你的 API 中使用上面的方法:

    module.exports.deleteCourse = function(req, res){
        var courseid = req.params.courseid;
        if(courseid){
            Course.removeOneWithDependencies(courseid, function(err){
                if(err){
                    return sendJSONResponse(res, 500, err);
                }
                else{
                    return sendJSONResponse(res, 204, null);
                }
            });
        } else{
            sendJSONResponse(res, 404, {"message":"NoId"});
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      • 2016-12-31
      相关资源
      最近更新 更多