Skip to content

Instantly share code, notes, and snippets.

@celsom3
Created February 23, 2017 20:25
Show Gist options
  • Save celsom3/d7da7a6e333b6087ca2f0211e3f9d7bf to your computer and use it in GitHub Desktop.
Save celsom3/d7da7a6e333b6087ca2f0211e3f9d7bf to your computer and use it in GitHub Desktop.
Mongoose plugin that removes makes it so front end doesn't get _id
const virtualId = (schema) => {
schema.add({ id: String });
schema.pre('save', function (next) {
this.id = this._id;
next();
});
const transform = function (doc, ret) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
return ret;
};
schema.options.toObject = schema.options.toObject || {};
schema.options.toJSON = schema.options.toJSON || {};
schema.options.toObject.transform = transform;
schema.options.toJSON.transform = transform;
schema.set('toObject', schema.options.toObject);
schema.set('toJSON', schema.options.toJSON);
};
export default virtualId;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment