title: How to properly delete an orphaned reference in MongoDB?
body: <p>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.  </p>
  
  <p>Here are my models:  </p>
  
  <pre><code>// ./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
  });
  </code></pre>
  
  <p>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:</p>
  
  <pre><code> // ./models/post
   PostSchema.pre('remove', function(next){
      this.model('User').remove({posts: this._id}, next);
   });
  </code></pre>
  
  <p>Here is the actual stack post: <a href="https://stackoverflow.com/questions/11904159/automatically-remove-referencing-objects-on-deletion-in-mongodb">Automatically remove referencing objects on deletion in MongoDB</a> .  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!</p>