@stenneepro/mongoose-soft-delete
Version:
Mongoose soft delete plugin
66 lines (65 loc) • 2.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
function default_1(schema, methods) {
schema.pre('save', function () {
if (typeof this.deleted === 'undefined') {
this.deleted = false;
}
});
const allMethods = getMethodsFromOptions(methods);
if (allMethods.length > 0) {
schema.pre(allMethods, async function () {
if (deletedIsNotAlreadyInQuery(this) && notIgnoreDeletedInOptions(this)) {
this.where({ deleted: false });
}
});
}
if (hasAggregateInOption(methods)) {
schema.pre('aggregate', async function () {
if (onlyDeletedInOptions(this)) {
this.pipeline().unshift({ $match: { deleted: true } });
}
else if (deletedIsNotAlreadyInAggregation(this) && notWithDeletedInOptions(this)) {
this.pipeline().unshift({ $match: { deleted: false } });
}
});
}
}
function getMethodsFromOptions(methods) {
if (methods === false) {
return [];
}
else if (Array.isArray(methods)) {
return methods;
}
return ['find', 'findOne', 'findOneAndUpdate', 'count', 'update', 'updateOne', 'updateMany', 'countDocuments'];
}
function hasAggregateInOption(methods) {
if (methods === false) {
return false;
}
else if (Array.isArray(methods)) {
return methods.includes('aggregate');
}
return true;
}
function deletedIsNotAlreadyInQuery(query) {
return typeof query.getQuery().deleted === 'undefined';
}
function notIgnoreDeletedInOptions(query) {
return query.getOptions().ignoreDeleted !== true;
}
function deletedIsNotAlreadyInAggregation(aggregation) {
const matches = aggregation.pipeline().filter(isPipelineMatch);
return !matches.some((match) => Object.keys(match['$match']).includes('deleted'));
}
function isPipelineMatch(pipeline) {
return Object.keys(pipeline).includes('$match');
}
function notWithDeletedInOptions(aggregation) {
return aggregation.options?.withDeleted !== true;
}
function onlyDeletedInOptions(aggregation) {
return aggregation.options?.onlyDeleted === true;
}