Advertisement
Guest User

Untitled

a guest
Apr 29th, 2016
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. var Model = require('mongoose').Model;
  2.  
  3.  
  4. function softRemove(schema) {
  5.  
  6. if (!schema.path('isRemoved')) {
  7. schema.add({ isRemoved : { type: Boolean, index: true, default: false } });
  8. }
  9.  
  10. if (!schema.path('removedAt')) {
  11. schema.add({ removedAt : { type: Date, index: true } });
  12. }
  13.  
  14. schema.static('remove', function(conditions, cb) {
  15. var softRemove = true;
  16.  
  17. if (conditions.$softRemove !== undefined) {
  18. softRemove = conditions.$softRemove;
  19. delete conditions.$softRemove;
  20. }
  21.  
  22. if (softRemove === false) {
  23. return Model.remove.apply(this, arguments);
  24. }
  25.  
  26. this.update(conditions, {
  27. $set: {
  28. isRemoved: true,
  29. removedAt: new Date()
  30. }
  31. }, cb);
  32. });
  33.  
  34. schema.static('restore', function(conditions, cb) {
  35. conditions.isRemoved = true;
  36. this.update(conditions, {
  37. $set : { isRemoved: false },
  38. $unset : { removedAt: 1 }
  39. }, cb);
  40. });
  41.  
  42. schema.method('remove', function(cb) {
  43. this.isRemoved = true;
  44. this.removedAt = new Date();
  45. this.save(cb);
  46. });
  47.  
  48. schema.method('restore', function(cb) {
  49. this.isRemoved = false;
  50. this.removedAt = undefined;
  51. this.save(cb);
  52. });
  53.  
  54. var setIsRemoved = function(next) {
  55. if (this._conditions.isRemoved === undefined) {
  56. this._conditions.isRemoved = false;
  57. }
  58. next(null);
  59. };
  60.  
  61. schema.pre('find' , setIsRemoved);
  62. schema.pre('findOne' , setIsRemoved);
  63. }
  64.  
  65.  
  66. module.exports = softRemove;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement