Discussion

Set or update field automatically without manual additional in Mongoose/MongoDB

I had a chance that I need to add new field for each schema in the MongoDB. First time, I thought I should add them manually for each model definition.

I investigated a better way and found that MongoDB provides plugin feature and provides hooks for each Mongoose events like find, save, update, delete.

For example, I want to add request field for each schema.

import mongoose from 'mongoose';
import Event, { eventSchema } from './models/Event';

mongoose.plugin((schema: any, options) => {
  schema.virtual('request').
  get(function() { return this._request; }).
  set(function(v) { this._request = v; });

  // pre hook before save any Mongoose schema
  schema.pre('save', async function () {
    // add request to schema
    schema.add({
      request: {
        type: String,
        ref: 'Request'
      }
    });

    const req = httpContext.get('request');
    this.request = req.requestId || null;
  });
}

This way, the request field is added for every model in the project.

That’s it!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *