Sling Academy
Home/Node.js/How to Store JSON data with Mongoose

How to Store JSON data with Mongoose

Last updated: December 30, 2023

Storing JSON data effectively in MongoDB via Mongoose entails understanding Schemas, data types, and methods for handling complex structures. This tutorial covers everything from basic setup to advanced concepts with practical examples.

Initializing Your Project

To start working with Mongoose and MongoDB, you need an initialized node project with the necessary modules. To set this up, use the following commands:

mkdir myjsonapp
cd myjsonapp
npm init -y
npm install mongoose

Connecting Mongoose to MongoDB

Establish a connection to MongoDB using Mongoose with this snippet:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });

Creating a Schema

Define a Mongoose schema that can accommodate a flexible JSON object:

const Schema = mongoose.Schema;
const jsonSchema = new Schema({ any: Schema.Types.Mixed });

Creating a Model

Once your schema is defined, create a model to interact with:

const JSONModel = mongoose.model('JSON', jsonSchema);

Basic CRUD Operations

Learn how to perform create, read, update, and delete operations:

Creating Documents

Create a new document within your JSON collection:

JSONModel.create({ any: { key: 'value' } })
    .then(doc => console.log(doc))
    .catch(err => console.error(err));

Reading Documents

Retrieve documents using simple queries:

JSONModel.find({ 'any.key': 'value' })
    .then(docs => console.log(docs))
    .catch(err => console.error(err));

Updating Documents

Here’s how to update documents in your collection:

JSONModel.updateOne({ 'any.key': 'value' }, { 'any.key': 'new value' })
    .then(result => console.log(result))
    .catch(err => console.error(err));

Deleting Documents

Delete documents with a specified condition:

JSONModel.deleteOne({ 'any.key': 'value' })
    .then(result => console.log(result))
    .catch(err => console.error(err));

Advanced Concepts

Dive into more complex use-cases such as nested schemas, validation, and indexing:

Nested Schemas

To handle nested JSON structures, create schemas for inner objects:

const childSchema = new Schema({ name: String });
const parentSchema = new Schema({ children: [childSchema] });
const Parent = mongoose.model('Parent', parentSchema);

Schema Validation

Ensure that your JSON data adheres to a certain format with Mongoose validation:

const validatedSchema = new Schema({
  name: { type: String, required: true },
  age: { type: Number, min: 18, required: true }
});
const ValidatedModel = mongoose.model('Person', validatedSchema);

Indexing for Performance

Speed up queries by defining indexes in your schema:

jsonSchema.index({ 'any.key': 1 });
JSONModel.createIndexes();

Conclusion

This tutorial has guided you through the process of storing and managing JSON data using Mongoose in a MongoDB database. By exploring schema creation, document manipulation, and advanced features, you’re now ready to build robust applications capable of handling complex JSON datasets.

Next Article: Mongoose $lookup operator (with examples)

Previous Article: Mongoose: How to get a random document

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