简体   繁体   中英

MongoDB: Updating arrays of sub documents after document deletion

I have an API in which I am deleting 'course' documents in the following way:

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

This is successful in deleting the course from the database, as is shown when attempting to find it by id.

The issue is that in user documents:

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

If the document was pushed to the courses array it remains after the deletion method.

So my question. Is there a relatively painless way to keep this document updated after deletes?

Thanks.

Add a class method for course using statics, where you delete both the course and its dependencies.

Assuming you are storing ids in courses array:

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

In case you are storing course documents in courses array you need to change the update query to:

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

Finally use the above method in your 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"});
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM