Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically remove referencing objects on deletion in MongoDB

Let's suppose I have a schema like this:

var Person = new Schema({     name: String });  var Assignment = new Schema({     name: String,     person: ObjectID }); 

If I delete a person, there can still be orphaned assignments left that reference a person that does not exist, which creates extraneous clutter in the database.

Is there a simple way to ensure that when a person is deleted, all corresponding references to that person will also be deleted?

like image 475
Peter Olson Avatar asked Aug 10 '12 14:08

Peter Olson


People also ask

How do I remove an object from an object in MongoDB?

To remove only a single object, provide it with another field to uniquely identify it. If you only want to remove the object that contains the title field from the array but wants to keep the object that contains the array, then please use the $pull operator. This answer will be of help.

What is difference between remove and delete in MongoDB?

They do the same. The difference is the values that return.

Which of the following function will remove collection in MongoDB?

MongoDB's remove() method is used to remove a document from the collection.


2 Answers

You can add your own 'remove' Mongoose middleware on the Person schema to remove that person from all other documents that reference it. In your middleware function, this is the Person document that's being removed.

Person.pre('remove', function(next) {     // Remove all the assignment docs that reference the removed person.     this.model('Assignment').remove({ person: this._id }, next); }); 
like image 148
JohnnyHK Avatar answered Sep 28 '22 07:09

JohnnyHK


If by "simple" you mean "built-in", then no. MongoDB is not a relational database after all. You need to implement your own cleaning mechanism.

like image 39
freakish Avatar answered Sep 28 '22 05:09

freakish