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?
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.
They do the same. The difference is the values that return.
MongoDB's remove() method is used to remove a document from the collection.
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); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With