VOOZH about

URL: https://www.geeksforgeeks.org/mongodb/mongoose-document-prototype-tojson-api/

⇱ Mongoose Document.prototype.toJSON() API - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mongoose Document.prototype.toJSON() API

Last Updated : 28 Apr, 2025

The Mongoose Document API.prototype.toJSON() method of the Mongoose API is used on the Document model. It allows to convert the result set into JSON object. The converted JSON object then can be used as a parameter to the JSON.stringify() method. Let us understand the toJSON() method using an example.

Syntax:

document.toJSON( options );

Parameters: This method accepts a single parameter as discussed below:

  • options: It is used to configure various properties for the method.

Return Value: This method returns the JavaScript JSON object.

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this: 

👁 Image
 

Database Structure: The database structure will look like this, the following documents are present in the collection.

👁 Image
 

Example 1: In this example, we are illustrating the functionality of toJSON() method. We are converting the result set in JSON object using the method.

Filename: app.js

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{
 _id: new ObjectId("639ede899fdf57759087a655"),
 name: 'Chintu',
 address: 'IND',
 orderNumber: 9,
 __v: 0
}

Example 2: In this example, we are illustrating the functionality of toJSON() method. We are converting the result in JSON object and then in string using JSON.stringify() method. At the end, we are displaying the type of both the converted values.

Filename: app.js

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

object
string

Reference: https://mongoosejs.com/docs/api/document.html#document_Document-toJSON

Comment

Explore