Node mongoose fill createdBy and updatedBy column with userId in every Model save and update

Viewed 145

In Node, Mongoose I am trying to achieve something like Laravel's created_by and updated_by columns, these 2 columns are automatically updated by the ORM in every INSERT and UPDATE operation to that particular table.

For example, below is the Material schema, here I want to store the createdBy and updatedBy column with userId whenever any user performs INSERT and UPDATE operations respectively in the materials collection.

I know this can be done while saving the records in particular controller method, but every time in every method I will have to add this and it becomes a pain, so I am looking for a solution where I can define something in the Model itself and it does the job just like the mongoose-delete package.

const mongoose = require('mongoose')
const mongoose_delete = require('mongoose-delete')

const materialSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    type: {
        type: String,
        required: true,
        enum: ['hard', 'soft'],
    },
    image: {
        type: String,
        default: null
    },
    active: {
        type: Boolean,
        default: true
    },
    createdBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        default: null
    },
    updatedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        default: null
    }
}, { timestamps: true })

materialSchema.plugin(mongoose_delete, { deletedAt : true, deletedBy : true, deletedByType: String })

const Material = mongoose.model("Material", materialSchema)
module.exports = Material
0 Answers
Related