Sling Academy
Home/Node.js/How to convert a Mongoose document to JSON

How to convert a Mongoose document to JSON

Last updated: December 30, 2023

Overview

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and translates between objects in code and their representation in MongoDB.

A Mongoose document is an instance of a model, representing a record in a MongoDB collection. These documents are rich objects with properties and methods that allow for powerful manipulations.

Working with Mongoose in Node.js often involves converting documents from your MongoDB database to JSON format. This tutorial guides you through the process, using modern JavaScript syntax and techniques.

Basic Conversion to JSON

Using .toJSON() Method

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const sampleSchema = new Schema({ name: String });
const SampleModel = mongoose.model('Sample', sampleSchema);

const sampleDoc = new SampleModel({ name: 'Sample Name' });

const json = sampleDoc.toJSON();
console.log(json); // { name: 'Sample Name', _id: ObjectId('...') }

Advanced Conversion Techniques

The .toJSON() method is customizable through schema options.

sampleSchema.set('toJSON', {
  transform: function(doc, ret, options) {
    delete ret._id;
    delete ret.__v;
    return ret;
  }
});

const jsonCustom = sampleDoc.toJSON();
console.log(jsonCustom); // { name: 'Sample Name' }

Working with Virtuals

Including virtuals in our JSON could require manual implementation or schema adjustments.

sampleSchema.virtual('nameLength').get(function() {
  return this.name.length;
});

const jsonWithVirtuals = sampleDoc.toJSON({ virtuals: true });
console.log(jsonWithVirtuals); // { name: 'Sample Name', nameLength: 12 }

Error Handling in Asynchronous Operations

We should always handle potential errors when serializing documents in an asynchronous context.

async function toJsonAsync(document) {
  try {
    return document.toJSON();
  } catch (error) {
    console.error(error);
    throw error;
  }
}

toJsonAsync(sampleDoc).then(console.log).catch(console.error);

Handling Circular References

Circular references can occur when a document references itself, directly or indirectly. Using third-party libraries like flatted could be a solution.

const flatted = require('flatted');

const circularDoc = new SampleModel({ name: 'Sample Name', selfRef: this });

const circularJson = flatted.stringify(circularDoc);
console.log(circularJson); // JSON string with resolved circular references

Conclusion

Converting a Mongoose document to JSON is a straightforward process in Node.js, aided greatly by the .toJSON() method. With these techniques under your belt, you’re equipped to handle a variety of data serialization scenarios within your applications.

Next Article: How to Perform Bulk Upsert in Mongoose

Previous Article: Mongoose Error: Schema Hasn’t Been Registered for Model

Series: Mongoose.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates