6

I am trying to change_id from mongoose schema to 'id' like is shown here MongoDB: output 'id' instead of '_id'

Duplicate the ID field.

Schema.virtual('id').get(function(){
    return this._id.toHexString();
});

// Ensure virtual fields are serialised.
Schema.set('toJSON', {
    virtuals: true
});

I am using typescript and Schema does not seem to have a 'virtual' method nor a 'set' method, and keyword 'this' is not bound in this context either. Who knows their typescript equivalents?

wendellmva
  • 1,896
  • 1
  • 26
  • 33
  • Where are you getting your type definitions for mongoose from? The definitely typed v4 d.ts file does provide the 'virtual' function on the Schema type (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/mongoose/v4/index.d.ts, line 740) As for the 'this' context, you may need to specify the type within the function signature .get(function(this: any) { (or something more appropriate, if you know the type) – Jye Lewis May 31 '18 at 01:12
  • Found any solution? I'm facing the same issue for virtuals, the this worked for the inner function – Webber May 05 '19 at 19:52
  • Please, share us your code, where your `Schema` is beind declared – Limbo May 05 '19 at 21:17
  • It seems to me that the Schema object you are trying to use is not of Mongoose. Please check if there is no other variable of same name. – XCEPTION May 08 '19 at 10:00

1 Answers1

3

This seemed to work with inheritance

import { Schema } from 'mongoose';

class BaseSchema extends Schema {
  constructor(args) {
    super();

    this.add(args);

    this.virtual('id').get(function(this: any) {
      return this._id.toHexString();
    });

    this.set('toObject', {
      virtuals: true,
    });

    this.set('toJSON', {
      virtuals: true,
    });
  }
}
Webber
  • 941
  • 11
  • 26
  • Thanks, that works for me too. The benefit of it is that you can use it globally too. It's returning _id and id. For everyone who wants to have the id being returned only, one of the options would be to apply a transform function to the set('toJSON') method as seen here: https://stackoverflow.com/a/42763286/7372307 – Dusty48 Oct 19 '19 at 13:19