Document.prototype.toObject()

Parameters
  • [options] «Object»

  • [options.getters=false] «Boolean» if true, apply all getters, including virtuals

  • [options.virtuals=false] «Boolean» if true, apply virtuals, including aliases. Use { getters: true, virtuals: false } to just apply getters, not virtuals

  • [options.aliases=true] «Boolean» if options.virtuals = true, you can set options.aliases = false to skip applying aliases. This option is a no-op if options.virtuals = false.

  • [options.minimize=true] «Boolean» if true, omit any empty objects from the output

  • [options.transform=null] «Function|null» if set, mongoose will call this function to allow you to transform the returned object

  • [options.depopulate=false] «Boolean» if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths.

  • [options.versionKey=true] «Boolean» if false, exclude the version key (__v by default) from the output

  • [options.flattenMaps=false] «Boolean» if true, convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject().

  • [options.useProjection=false] «Boolean»

    • If true, omits fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that has select: false in the schema.
Returns:
  • «Object» js object

Converts this document into a plain-old JavaScript object (POJO).

Buffers are converted to instances of mongodb.Binary for proper storage.

Options:

  • getters apply all getters (path and virtual getters), defaults to false
  • aliases apply all aliases if virtuals=true, defaults to true
  • virtuals apply virtual getters (can override getters option), defaults to false
  • minimize remove empty objects, defaults to true
  • transform a transform function to apply to the resulting document before returning
  • depopulate depopulate any populated paths, replacing them with their original refs, defaults to false
  • versionKey whether to include the version key, defaults to true
  • flattenMaps convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false
  • useProjection set to true to omit fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that has select: false in the schema.

Getters/Virtuals

Example of only applying path getters

  1. doc.toObject({ getters: true, virtuals: false })

Example of only applying virtual getters

  1. doc.toObject({ virtuals: true })

Example of applying both path and virtual getters

  1. doc.toObject({ getters: true })

To apply these options to every document of your schema by default, set your schemas toObject option to the same argument.

  1. schema.set('toObject', { virtuals: true })

Transform

We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional transform function.

Transform functions receive three arguments

  1. function (doc, ret, options) {}
  • doc The mongoose document which is being converted
  • ret The plain object representation which has been converted
  • options The options in use (either schema options or the options passed inline)

Example

  1. // specify the transform schema option
  2. if (!schema.options.toObject) schema.options.toObject = {};
  3. schema.options.toObject.transform = function (doc, ret, options) {
  4. // remove the _id of every document before returning the result
  5. delete ret._id;
  6. return ret;
  7. }
  8. // without the transformation in the schema
  9. doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  10. // with the transformation
  11. doc.toObject(); // { name: 'Wreck-it Ralph' }

With transformations we can do a lot more than remove properties. We can even return completely new customized objects:

  1. if (!schema.options.toObject) schema.options.toObject = {};
  2. schema.options.toObject.transform = function (doc, ret, options) {
  3. return { movie: ret.name }
  4. }
  5. // without the transformation in the schema
  6. doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  7. // with the transformation
  8. doc.toObject(); // { movie: 'Wreck-it Ralph' }

Note: if a transform function returns undefined, the return value will be ignored.

Transformations may also be applied inline, overridding any transform set in the options:

  1. function xform (doc, ret, options) {
  2. return { inline: ret.name, custom: true }
  3. }
  4. // pass the transform as an inline option
  5. doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }

If you want to skip transformations, use transform: false:

  1. schema.options.toObject.hide = '_id';
  2. schema.options.toObject.transform = function (doc, ret, options) {
  3. if (options.hide) {
  4. options.hide.split(' ').forEach(function (prop) {
  5. delete ret[prop];
  6. });
  7. }
  8. return ret;
  9. }
  10. const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
  11. doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
  12. doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
  13. doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }

If you pass a transform in toObject() options, Mongoose will apply the transform to subdocuments in addition to the top-level document. Similarly, transform: false skips transforms for all subdocuments.

Note that this is behavior is different for transforms defined in the schema

if you define a transform in schema.options.toObject.transform, that transform will not apply to subdocuments.

  1. const memberSchema = new Schema({ name: String, email: String });
  2. const groupSchema = new Schema({ members: [memberSchema], name: String, email });
  3. const Group = mongoose.model('Group', groupSchema);
  4. const doc = new Group({
  5. name: 'Engineering',
  6. email: 'dev@mongoosejs.io',
  7. members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
  8. });
  9. // Removes `email` from both top-level document **and** array elements
  10. // { name: 'Engineering', members: [{ name: 'Val' }] }
  11. doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } });

Transforms, like all of these options, are also available for toJSON. See this guide to JSON.stringify() to learn why toJSON() and toObject() are separate functions.

See schema options for some more details.

During save, no custom options are applied to the document before being sent to the database.