How do I create an automatic field in Mongoose?

Go To StackoverFlow.com

4

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?

2012-04-03 21:52
by Shamoon


10

CompanySchema.pre('save', function(next) {
  this.id = this._id;
  next();
});
2012-04-05 15:07
by Shamoon
For anyone coming along later, it seems Mongoose now automatically adds a virtual attribute 'id', so this is probably no longer needed (at least as of Mongoose 3.8.x) - ChrisV 2014-11-02 10:04
Ads