Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly delete an orphaned reference in MongoDB?

So, I am building a small blog-like project in Node, and I am running into an issue with orphaned database references. I have two models in separate files that reference each other.

Here are my models:

// ./models/user   
Var UserSchema = mongoose.Schema({
  name: String,
  posts: [{type: mongoose.SchemaTypes.ObjectId, ref:'Post'}]
});

//  ./models/post
var PostSchema = mongoose.Schema({
  title:String,
  post_body: String,
  posted_by: mongoose.SchemaTypes.ObjectId
});

My question is when you delete say, a Post, how would you delete the reference in the User's post array? My thinking was I could create a middleware to run before the delete route and delete the reference in the User's post array before I actually delete the post. Would that be considered the best way to go about it? I found a post on Stack that uses a 'pre' function in the schema like this:

 // ./models/post
 PostSchema.pre('remove', function(next){
    this.model('User').remove({posts: this._id}, next);
 });

Here is the actual stack post: Automatically remove referencing objects on deletion in MongoDB . I could not get this work though. I did ,however, implement a custom middleware to delete the references, but feel it might not be best practice. Any tips/advice would be greatly appreciated. Thanks!

like image 244
elloM8 Avatar asked Jan 06 '23 10:01

elloM8


1 Answers

You don't want .remove() here but you want .update() with $pull instead:

PostSchema.pre('update',function(next) {
    this.model('User').update(
        { },
        { "$pull": { "posts": this._id } },
        { "multi": true },
        next
    );
})

That's the correct operation to remove something from an array. The "multi" makes sure that the "post" would be removed for all User objects that reference it, thought it probably really is only one document anyway.

The .remove() method is for "removing" whole documents. The .update() method makes "changes" to documents.

like image 177
Blakes Seven Avatar answered Jan 17 '23 02:01

Blakes Seven