mongo-softdelete

Mongo wrapper that supports soft delete on collections

Usage no npm install needed!

<script type="module">
  import mongoSoftdelete from 'https://cdn.skypack.dev/mongo-softdelete';
</script>

README

mongo-softdelete

Wrapper for a mongo collection that soft delete documents. Soft delete documents is not remove from the collection but instead the property _deleted has been added to the document. Queries executed from the wrapped collection will ignore soft deleted documents.

A soft deleted document will have the property _deleted set to a time stamp.

{
  _deleted: new Date(),
  data: ...
}

The following methods are not supported:

  • distinct
  • createIndex
  • ensureIndex
  • mapReduce
  • group
  • geoNear
  • geoHaystackSearch
  • aggregate

Usage:

var mongoSsoftDelete = require('mongo-softdelete');

mongodb.Db.connect(connection, function(err, db){
  if(err) throw err;
  
  database.collection('softDeleteCollection', function (err, col) {
    if(err) throw err;
    
    var softDeleteCollection = mongoSsoftDelete(col);
    
    softDeleteCollection.insert({a: 1}, function(err, doc) {
      if(err) throw err;
      
      softDeleteCollection.remove(function(err, doc) {
        if(err) throw err;
      
        softDeleteCollection.findOne({a: 1}, function (err, doc) {
          if(err) throw err;
      
          // does not return the soft deleted document - but it still exist in the collection
          console.log(doc);
        });
      })
    })
  });
});