soft-delete-plugin-mongoose
Version:
a mongoose plugin that allows you to soft delete documents and restore them (for JS & TS)
457 lines (456 loc) • 22.7 kB
JavaScript
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var mongoose_1 = __importDefault(require("mongoose"));
var models_1 = require("./models");
var utils_1 = require("../src/utils");
describe('Aggregation Pipeline Soft Delete Tests', function () {
var testUser1;
var testUser2;
var testPost1;
var testPost2;
var testComment1;
var testComment2;
beforeAll(function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Connect to test database
return [4 /*yield*/, mongoose_1.default.connect('mongodb://localhost:27017/test?directConnection=true')];
case 1:
// Connect to test database
_a.sent();
return [2 /*return*/];
}
});
}); });
beforeEach(function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Clean up collections
return [4 /*yield*/, models_1.User.deleteMany({})];
case 1:
// Clean up collections
_a.sent();
return [4 /*yield*/, models_1.Post.deleteMany({})];
case 2:
_a.sent();
return [4 /*yield*/, models_1.Comment.deleteMany({})];
case 3:
_a.sent();
return [4 /*yield*/, models_1.User.create({
name: 'John Doe',
email: 'john@example.com',
age: 30,
})];
case 4:
// Create test users
testUser1 = _a.sent();
return [4 /*yield*/, models_1.User.create({
name: 'Jane Smith',
email: 'jane@example.com',
age: 25,
})];
case 5:
testUser2 = _a.sent();
return [4 /*yield*/, models_1.Post.create({
title: 'First Post',
content: 'This is the first post content',
author: testUser1._id,
tags: ['tech', 'programming'],
isPublished: true,
})];
case 6:
// Create test posts
testPost1 = _a.sent();
return [4 /*yield*/, models_1.Post.create({
title: 'Second Post',
content: 'This is the second post content',
author: testUser2._id,
tags: ['lifestyle', 'travel'],
isPublished: true,
})];
case 7:
testPost2 = _a.sent();
return [4 /*yield*/, models_1.Comment.create({
content: 'Great post!',
author: testUser2._id,
post: testPost1._id,
})];
case 8:
// Create test comments
testComment1 = _a.sent();
return [4 /*yield*/, models_1.Comment.create({
content: 'Thanks for sharing',
author: testUser1._id,
post: testPost2._id,
})];
case 9:
testComment2 = _a.sent();
return [2 /*return*/];
}
});
}); });
afterAll(function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, models_1.User.deleteMany()];
case 1:
_a.sent();
return [4 /*yield*/, models_1.Post.deleteMany()];
case 2:
_a.sent();
return [4 /*yield*/, models_1.Comment.deleteMany()];
case 3:
_a.sent();
return [4 /*yield*/, mongoose_1.default.disconnect()];
case 4:
_a.sent();
return [2 /*return*/];
}
});
}); });
describe('$lookup with soft deleted documents', function () {
it('should filter out soft deleted users from post aggregation', function () { return __awaiter(void 0, void 0, void 0, function () {
var postsWithAuthors, postByDeletedUser, postByActiveUser;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Soft delete one user
return [4 /*yield*/, models_1.User.softDelete({ _id: testUser1._id })];
case 1:
// Soft delete one user
_a.sent();
return [4 /*yield*/, models_1.Post.aggregate([
{
$lookup: {
from: 'users',
localField: 'author',
foreignField: '_id',
as: 'authorDetails',
},
},
{
$project: {
title: 1,
authorDetails: 1,
},
},
])];
case 2:
postsWithAuthors = _a.sent();
expect(postsWithAuthors).toHaveLength(2);
postByDeletedUser = postsWithAuthors.find(function (post) { return post.title === 'First Post'; });
expect(postByDeletedUser.authorDetails).toHaveLength(0);
postByActiveUser = postsWithAuthors.find(function (post) { return post.title === 'Second Post'; });
expect(postByActiveUser.authorDetails).toHaveLength(1);
expect(postByActiveUser.authorDetails[0].name).toBe('Jane Smith');
return [2 /*return*/];
}
});
}); });
it('should filter out soft deleted posts from comment aggregation', function () { return __awaiter(void 0, void 0, void 0, function () {
var commentsWithPosts, commentOnDeletedPost, commentOnActivePost;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Soft delete one post
return [4 /*yield*/, models_1.Post.softDelete({ _id: testPost1._id })];
case 1:
// Soft delete one post
_a.sent();
return [4 /*yield*/, models_1.Comment.aggregate([
{
$lookup: {
from: 'posts',
localField: 'post',
foreignField: '_id',
as: 'postDetails',
},
},
{
$project: {
content: 1,
postDetails: 1,
},
},
])];
case 2:
commentsWithPosts = _a.sent();
expect(commentsWithPosts).toHaveLength(2);
commentOnDeletedPost = commentsWithPosts.find(function (comment) { return comment.content === 'Great post!'; });
expect(commentOnDeletedPost.postDetails).toHaveLength(0);
commentOnActivePost = commentsWithPosts.find(function (comment) { return comment.content === 'Thanks for sharing'; });
expect(commentOnActivePost.postDetails).toHaveLength(1);
expect(commentOnActivePost.postDetails[0].title).toBe('Second Post');
return [2 /*return*/];
}
});
}); });
it('should handle multiple lookups with soft deleted documents', function () { return __awaiter(void 0, void 0, void 0, function () {
var commentsWithDetails, firstComment, secondComment;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Soft delete one user and one post
return [4 /*yield*/, models_1.User.softDelete({ _id: testUser1._id })];
case 1:
// Soft delete one user and one post
_a.sent();
return [4 /*yield*/, models_1.Post.softDelete({ _id: testPost2._id })];
case 2:
_a.sent();
return [4 /*yield*/, models_1.Comment.aggregate([
{
$lookup: {
from: 'users',
localField: 'author',
foreignField: '_id',
as: 'authorDetails',
},
},
{
$lookup: {
from: 'posts',
localField: 'post',
foreignField: '_id',
as: 'postDetails',
},
},
{
$project: {
content: 1,
authorDetails: 1,
postDetails: 1,
},
},
])];
case 3:
commentsWithDetails = _a.sent();
expect(commentsWithDetails).toHaveLength(2);
firstComment = commentsWithDetails.find(function (comment) { return comment.content === 'Great post!'; });
expect(firstComment.authorDetails).toHaveLength(1); // User2 is active
expect(firstComment.postDetails).toHaveLength(1); // Post1 is active
secondComment = commentsWithDetails.find(function (comment) { return comment.content === 'Thanks for sharing'; });
expect(secondComment.authorDetails).toHaveLength(0); // User1 is deleted
expect(secondComment.postDetails).toHaveLength(0); // Post2 is deleted
return [2 /*return*/];
}
});
}); });
});
describe('$match with soft deleted documents', function () {
it('should exclude soft deleted documents in match stage', function () { return __awaiter(void 0, void 0, void 0, function () {
var activeUsers;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Soft delete one user
return [4 /*yield*/, models_1.User.softDelete({ _id: testUser1._id })];
case 1:
// Soft delete one user
_a.sent();
return [4 /*yield*/, models_1.User.aggregate([
{
$match: {
age: { $gte: 25 },
},
},
{
$project: {
name: 1,
email: 1,
age: 1,
},
},
])];
case 2:
activeUsers = _a.sent();
// Should only return active user
expect(activeUsers).toHaveLength(1);
expect(activeUsers[0].name).toBe('Jane Smith');
return [2 /*return*/];
}
});
}); });
it('should allow explicit search for deleted documents', function () { return __awaiter(void 0, void 0, void 0, function () {
var deletedUsers;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Soft delete one user
return [4 /*yield*/, models_1.User.softDelete({ _id: testUser1._id })];
case 1:
// Soft delete one user
_a.sent();
return [4 /*yield*/, models_1.User.aggregate([
{
$match: {
isDeleted: true,
},
},
{
$project: {
name: 1,
email: 1,
isDeleted: 1,
},
},
])];
case 2:
deletedUsers = _a.sent();
// Should return the deleted user
expect(deletedUsers).toHaveLength(1);
expect(deletedUsers[0].name).toBe('John Doe');
expect(deletedUsers[0].isDeleted).toBe(true);
return [2 /*return*/];
}
});
}); });
});
describe('Complex aggregation scenarios', function () {
it('should handle nested comments with soft deleted parents', function () { return __awaiter(void 0, void 0, void 0, function () {
var nestedComment, commentsWithParents, nestedCommentResult;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, models_1.Comment.create({
content: 'Reply to first comment',
author: testUser1._id,
post: testPost1._id,
parentComment: testComment1._id,
})];
case 1:
nestedComment = _a.sent();
// Soft delete the parent comment
return [4 /*yield*/, models_1.Comment.softDelete({ _id: testComment1._id })];
case 2:
// Soft delete the parent comment
_a.sent();
return [4 /*yield*/, models_1.Comment.aggregate([
{
$lookup: {
from: 'comments',
localField: 'parentComment',
foreignField: '_id',
as: 'parentCommentDetails',
},
},
{
$project: {
content: 1,
parentCommentDetails: 1,
},
},
])];
case 3:
commentsWithParents = _a.sent();
nestedCommentResult = commentsWithParents.find(function (comment) { return comment.content === 'Reply to first comment'; });
// Should have empty parentCommentDetails since parent is soft deleted
expect(nestedCommentResult.parentCommentDetails).toHaveLength(0);
return [2 /*return*/];
}
});
}); });
it('should work with grouping and soft deleted documents', function () { return __awaiter(void 0, void 0, void 0, function () {
var commentsByPost;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Soft delete one post
return [4 /*yield*/, models_1.Post.softDelete({ _id: testPost1._id })];
case 1:
// Soft delete one post
_a.sent();
return [4 /*yield*/, models_1.Comment.aggregate([
{
$lookup: {
from: 'posts',
localField: 'post',
foreignField: '_id',
as: 'postDetails',
},
},
{
$match: {
'postDetails.0': { $exists: true }, // Only comments with existing posts
},
},
{
$group: {
_id: '$post',
commentCount: { $sum: 1 },
postTitle: { $first: { $arrayElemAt: ['$postDetails.title', 0] } },
},
},
])];
case 2:
commentsByPost = _a.sent();
// Should only have one group (for the active post)
expect(commentsByPost).toHaveLength(1);
expect(commentsByPost[0].postTitle).toBe('Second Post');
expect(commentsByPost[0].commentCount).toBe(1);
return [2 /*return*/];
}
});
}); });
});
describe('utils', function () {
it('should overwrite match stage with isDeleted query', function () {
var pipeline = [
{
$match: {
user: '123',
}
}
];
var result = utils_1.overwriteAggregatePipeline(pipeline);
expect(result).toEqual([
{
$match: {
user: '123',
isDeleted: false,
}
}
]);
});
});
});