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.