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 setoptions.aliases = false
to skip applying aliases. This option is a no-op ifoptions.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 oftoObject()
.[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.
- If true, omits fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that has
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 falsealiases
apply all aliases ifvirtuals=true
, defaults to truevirtuals
apply virtual getters (can overridegetters
option), defaults to falseminimize
remove empty objects, defaults to truetransform
a transform function to apply to the resulting document before returningdepopulate
depopulate any populated paths, replacing them with their original refs, defaults to falseversionKey
whether to include the version key, defaults to trueflattenMaps
convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to falseuseProjection
set totrue
to omit fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that hasselect: false
in the schema.
Getters/Virtuals
Example of only applying path getters
doc.toObject({ getters: true, virtuals: false })
Example of only applying virtual getters
doc.toObject({ virtuals: true })
Example of applying both path and virtual getters
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.
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
function (doc, ret, options) {}
doc
The mongoose document which is being convertedret
The plain object representation which has been convertedoptions
The options in use (either schema options or the options passed inline)
Example
// specify the transform schema option
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
// remove the _id of every document before returning the result
delete ret._id;
return ret;
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
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:
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
return { movie: ret.name }
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
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:
function xform (doc, ret, options) {
return { inline: ret.name, custom: true }
}
// pass the transform as an inline option
doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }
If you want to skip transformations, use transform: false
:
schema.options.toObject.hide = '_id';
schema.options.toObject.transform = function (doc, ret, options) {
if (options.hide) {
options.hide.split(' ').forEach(function (prop) {
delete ret[prop];
});
}
return ret;
}
const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
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.
const memberSchema = new Schema({ name: String, email: String });
const groupSchema = new Schema({ members: [memberSchema], name: String, email });
const Group = mongoose.model('Group', groupSchema);
const doc = new Group({
name: 'Engineering',
email: 'dev@mongoosejs.io',
members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
});
// Removes `email` from both top-level document **and** array elements
// { name: 'Engineering', members: [{ name: 'Val' }] }
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.