The Mongoose documentation for toObject lists features, options, and gives examples of functionality of toObject
.
The Mongoose documentation for toJSON
says the options are the same as toObject, but doesn't explain what toJSON
does. Elsewhere the documentation says
toJSON is exactly the same as the toObject option but only applies when the document's toJSON method is called.
Is toJSON
an alias of toObject
? If not, what are the differences?
Mongoose toObject and toJSON transform behavior with sub-documents. Published on Tuesday, June 7, 2016. Mongoose supports two Schema options to transform Objects after querying MongoDb: toObject and toJSON . In general you can access the returned object in the transform method toObject or toJSON as described in the ...
The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable.
Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
A look at the source code reveals that both methods call an internal $toObject
method, but with toJSON
passing a second, true
parameter:
Document.prototype.toObject = function (options) { return this.$toObject(options); }; ... Document.prototype.toJSON = function (options) { return this.$toObject(options, true); };
That second parameter determines whether $toObject
uses the toJSON
or toObject
schema options for its defaults. So unless those schema options are configured differently, the two methods are identical.
Like JohnnyHK's anwser said, there is no difference between toJSON
and toObject
. My guess is that, toJSON
was created to support the JSON.stringify
method.
From the MDN document, if an object has the toJSON
property as a function, JSON.stringify
will use the toJSON
function to serialize the object instead of the object itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With