@aequum/mongoose
Version:
aequum mongoose tools for repository, pagination, CRUD/CRUDL, configs and utils
59 lines (58 loc) • 1.88 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchemaWithVirtualID = void 0;
exports.schemaTransformsForVirtualID = schemaTransformsForVirtualID;
/* eslint-disable @typescript-eslint/no-empty-object-type */
const mongoose_1 = require("mongoose");
function schemaTransformsForVirtualID(schema, toJSONOptions, toObjectOptions, removeVersion = true) {
const transformOptions = [
['toObject', toObjectOptions || {}],
['toJSON', toJSONOptions || {}],
];
Object.defineProperty(schema, '__hasVirtualID__', {
value: true,
writable: false,
enumerable: false
});
for (const [key, options] of transformOptions)
schema.set(key, Object.assign({}, options, {
virtuals: true,
transform: (doc, ret, opt) => {
if (typeof options?.transform === 'function')
options?.transform(doc, ret, opt);
delete ret._id;
if (removeVersion)
delete ret.__v;
},
}));
return schema;
}
/** @ignore */
function virtualIdOptions(options) {
const opts = options || {};
if (!opts.virtuals)
opts.virtuals = {};
if (!opts.virtuals.id)
opts.virtuals.id = {};
Object.assign(opts.virtuals.id, {
get: function () {
return this._id.toString();
},
set: function (value) {
this._id = value;
},
});
}
/**
* Mongoose Schema with a virtual `id` property
* combine with `schemaTransformsForVirtualID`
* to remove `_id` and `__v` properties.
*
* @see {@link schemaTransformsForVirtualID}
*/
class SchemaWithVirtualID extends mongoose_1.Schema {
constructor(definition, options) {
super(definition, virtualIdOptions(options));
}
}
exports.SchemaWithVirtualID = SchemaWithVirtualID;