Is it possible to save document rum after removing it using a middleware in Mongoose?

0

I'm developing a system that requires some MongoDB documents to be kept in a database even if they have been removed, for historical purposes, so I created a plugin that inserts 3 fields:

  • criadoEm
  • atualizadoEm
  • apagadoEm

The fields criadoEm and atualizadoEm do not see problems for updating when saving.

But the apagadoEm field should be updated when doc.remove () is called.

I thought of using post middleware for this purpose, reinserting the document into the database, is there another method?

Code sample:

module.exports = exports = function historicoPlugin(schema, options) {
    const criadoEm = 'criadoEm';
    const atualizadoEm = 'atualizadoEm';
    schema.add({
        criadoEm: Date
    });
    schema.add({
        atualizadoEm: Date
    });
    if (options) {
        if (options.criadoEm) {
            if (options.criadoEm.index) {
                schema.path(criadoEm).index(options.criadoEm.index);
            }
            if (options.atualizadoEm) {
                if (options.atualizadoEm.index) {}
                schema.path(atualizadoEm).index(options.atualizadoEm.index);
            }
            if (options.removidoEm && options.removidoEm.enabled) {
                const removidoEm = 'removidoEm';
                schema.add({
                    removidoEm: Date
                });
                if (options.removidoEm.index) {
                    schema.path(removidoEm).index(options.removidoEm.index);
                }
                schema.post('remove', function (doc) {
                    doc.removidoEm = new Date();
                    doc.save();
                });
            }
        }
    }

    schema.pre('save', function (next) {
        if (this.criadoEm !== undefined)
            this.criadoEm = new Date();

        this.atualizadoEm = new Date();

        next();
    });

}
    
asked by anonymous 16.07.2018 / 21:06

0 answers