How do I create an automatic field in Mongoose?

mongodb, mongoose, node.js

Solution

CompanySchema.pre('save', function(next) {
  this.id = this._id;
  next();
});

Problem

I have a model that looks like: ``` var CompanySchema = new Schema({ name: String , logoUrl: String , created: { type: Date, default: new Date().toUTCString() } , deleted: { type: Date, default: null } }); ``` I want to have a field called `id` as well (this is on top of the `_id` that already gets added). So how can I create the `id` field and have it automatically assigned to the value of `_id`?

Original source