Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Mongoose toObject and toJSON?

Tags:

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?

like image 934
steampowered Avatar asked Jul 31 '15 23:07

steampowered


People also ask

What is toJSON in Mongoose?

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 ...

What is Version Key in Mongoose?

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.

What is Mongoose schema and model?

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.


2 Answers

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 image 126
JohnnyHK Avatar answered Sep 21 '22 09:09

JohnnyHK


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.

like image 20
Anh Cao Avatar answered Sep 17 '22 09:09

Anh Cao