Jeach
Jeach

Reputation: 9052

Mongoose - Implement a function for ALL schema's (not on each schema)

I've seen many examples where it is shown how to implement a custom transformation function on a schema (toJSON() for example, but could be another name).

But I don't want to keep duplicating that code for 'each' schema. Is there a way to implement it once globally, such that it will automatically be inherited by ALL schemas?

Here is an example of the toJSON() I would like to have.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/**
 * toJSON implementation
 */
Schema.options.toJSON = {
  transform: function(doc, ret, options) {
    ret.id = ret._id;
    delete ret._id;
    delete ret.__v;
    return ret;
  }
};

I would like to add a few additional 'global' functions like the one above.

Update 2018.02.13: I define my models (schema's) in distinct modules (each their own .js file). So for example, I will have an account/schema.js module, an profile/schema.js module and so forth. I have at least 30+ schemas in my application.

Upvotes: 2

Views: 664

Answers (2)

Fraction
Fraction

Reputation: 12984

You can use Mongoose.prototype.set():

var mongoose = require('mongoose');
mongoose.set('TOJSON', {
  transform: function(doc, ret, options) {
    ret.id = ret._id;
    delete ret._id;
    delete ret.__v;
    return ret;
  }
}

Upvotes: 0

tverghis
tverghis

Reputation: 999

Edit: You might also be interested in Mongoose Plugins.

--

You can define that function in a shared module, and import that module wherever you define your schemas. Then, you can achieve what you want by setting your schema's toJSON to this central, shared toJSON function.

/** sharedFunctions.js **/
function toJSON(...) { ... }
module.exports = { toJSON: toJSON }

--

/** userSchema.js **/
const sharedFunctions = require('path/to/sharedFunctions');
...
// In your schema definition:
  toJSON: sharedFunctions.toJSON

Upvotes: 2

Related Questions