Open In App

Mongoose Document.prototype.toJSON() API

Last Updated : 20 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

 

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

 

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

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const Customer = connectionObject.model(
    "Customer",
    new mongoose.Schema({
        name: String,
        address: String,
        orderNumber: Number,
    })
);
  
Customer.findById("639ede899fdf57759087a655").then(res => {
    const jsonObject = res.toJSON();
    console.log(jsonObject)
}).catch(err => {
    console.log(err);
})


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

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const customerSchema = new mongoose.Schema({
    name: String,
    address: String,
    orderNumber: Number,
})
  
const Customer = connectionObject.model(
    "Customer", customerSchema
);
  
customerSchema.set('toJSON', { virtuals: true });
  
Customer
    .findById("639ede899fdf57759087a655")
    .exec((error, result) => {
        if (error) {
            console.log(error);
        } else {
            console.log(typeof result);
            const jsonObject = result.toJSON();
            const stringConverted = JSON.stringify(jsonObject);
            console.log(typeof stringConverted);
        }
    });


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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads