How to Create and Validate JSON Schema in MongoDB?
Last Updated :
23 May, 2024
JSON Schema validation in MongoDB allows you to enforce the structure of documents in a collection. This ensures data integrity by validating documents against defined schemas before they are inserted or updated.
In this article, we will cover how to create and validate JSON Schema in MongoDB using different approaches, provide a step-by-step guide to set up the application, and include an example for better understanding.
Validating JSON schema involves defining the required schema and creating a model in Mongoose. We can validate the JSON Schema in MongoDB using the approaches mentioned below:
Creating JSON Schema
Using MongoDB Shell
db.createCollection("collection_name", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["field1", "field2"],
properties: {
field1: {
bsonType: "string",
description: "must be a string and is required"
},
field2: {
bsonType: "int",
minimum: 0,
description:
"must be an integer greater than or equal to 0
and is required"
}
}
}
}
});
Using Mongoose (ODM for MongoDB)
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
field1: {
type: String,
required: true
},
field2: {
type: Number,
min: 0,
required: true
}
});
const Model = mongoose.model('Model', schema);
Using MongoDB Shell
The MongoDB Shell approach directly interacts with the MongoDB server to create collections with schema validation.
Steps:
- Connect to your MongoDB server using the shell.
- Execute the db.createCollection command with the validator option to define your JSON Schema.
Example:
Microsoft Windows [Version 10.0.22631.3593]
(c) Microsoft Corporation. All rights reserved.
C:\Users\Jeetu>mongosh
Current Mongosh Log ID: 664c29b41fa4c614a5def71c
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.1.5
Using MongoDB: 7.0.6
Using Mongosh: 2.1.5
mongosh 2.2.6 is available for download: https://www.mongodb.com/try/download/shell
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
The server generated these startup warnings when booting
2024-05-20T22:25:15.613+05:30: Access control is not enabled for the database.
Read and write access to data and configuration is unrestricted
test> use myDatabase;
switched to db myDatabase
myDatabase> db.createCollection("users", {
... validator: {
... $jsonSchema: {
... bsonType: "object",
... required: ["name", "age"],
... properties: {
... name: {
... bsonType: "string",
... description: "must be a string and is required"
... },
... age: {
... bsonType: "int",
... minimum: 0,
... description: "must be an integer greater than or equal to 0
and is required"
... }
... }
... }
... }
... });
{ ok: 1 }
myDatabase> db.users.insertOne({ name: "Alice", age: 25 });
{
acknowledged: true,
insertedId: ObjectId('664c29c81fa4c614a5def71d')
}
myDatabase> db.users.insertOne({ name: "Bob" });
Uncaught:
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId('664c29d11fa4c614a5def71e'),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'required',
specifiedAs: { required: [ 'name', 'age' ] },
missingProperties: [ 'age' ]
}
]
}
}
myDatabase> db.users.insertOne({ name: "Charlie", age: "twenty-five" });
Uncaught:
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId('664c29d81fa4c614a5def71f'),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'age',
description: 'must be an integer greater than or equal to 0 and is required',
details: [
{
operatorName: 'bsonType',
specifiedAs: { bsonType: 'int' },
reason: 'type did not match',
consideredValue: 'twenty-five',
consideredType: 'string'
}
]
}
]
}
]
}
}
myDatabase> db.users.insertOne({ name: "Dave", age: -5 });
Uncaught:
MongoServerError: Document failed validation
Additional information: {
failingDocumentId: ObjectId('664c29e21fa4c614a5def720'),
details: {
operatorName: '$jsonSchema',
schemaRulesNotSatisfied: [
{
operatorName: 'properties',
propertiesNotSatisfied: [
{
propertyName: 'age',
description: 'must be an integer greater than or equal to 0 and is required',
details: [
{
operatorName: 'minimum',
specifiedAs: { minimum: 0 },
reason: 'comparison failed',
consideredValue: -5
}
]
}
]
}
]
}
}
Using Mongoose
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js.
Steps:
npm install mongoose
- Define a schema using Mongoose’s schema definition.
- Create a model using the defined schema.
JavaScript
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myDatabase');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
age: {
type: Number,
min: 0,
required: true
}
});
const User = mongoose.model('User', userSchema);
const newUser = new User({ name: 'Alice', age: 25 });
newUser.save().then(() =>
console.log('User saved')).catch(err => console.error(err));
// Inserting a user with missing 'age' field
const invalidUser = new User({ name: 'Bob' });
invalidUser.save()
.then(() => console.log('Invalid user saved'))
.catch(err => console.error('Error saving invalid user:', err));
// Inserting a user with negative age
const negativeAgeUser = new User({ name: 'Charlie', age: -5 });
negativeAgeUser.save()
.then(() => console.log('Negative age user saved'))
.catch(err => console.error('Error saving negative age user:', err));
Output:
Jeetu@DESKTOP-U3OB8C4 MINGW64 /d/jeetu/mongodb
$ node index.js
Error saving invalid user: Error: User validation failed: age: Path `age` is required.
at ValidationError.inspect (D:\jeetu\mongodb\node_modules\mongoose\lib\error\validation.js:50:26)
at formatValue (node:internal/util/inspect:805:19)
at inspect (node:internal/util/inspect:364:10)
at formatWithOptionsInternal (node:internal/util/inspect:2298:40)
at formatWithOptions (node:internal/util/inspect:2160:10)
at console.value (node:internal/console/constructor:351:14)
at console.warn (node:internal/console/constructor:384:61)
at D:\jeetu\mongodb\index.js:115:27
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
errors: {
age: ValidatorError: Path `age` is required.
at validate (D:\jeetu\mongodb\node_modules\mongoose\lib\schemaType.js:1385:13)
at SchemaType.doValidate (D:\jeetu\mongodb\node_modules\mongoose\lib\schemaType.js:1369:7)
at D:\jeetu\mongodb\node_modules\mongoose\lib\document.js:3042:18
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
properties: [Object],
kind: 'required',
path: 'age',
value: undefined,
reason: undefined,
[Symbol(mongoose#validatorError)]: true
}
},
_message: 'User validation failed'
}
Error saving negative age user: Error: User validation failed: age: Path `age` (-5) is less than minimum
allowed value (0).
at ValidationError.inspect (D:\jeetu\mongodb\node_modules\mongoose\lib\error\validation.js:50:26)
at formatValue (node:internal/util/inspect:805:19)
at inspect (node:internal/util/inspect:364:10)
at formatWithOptionsInternal (node:internal/util/inspect:2298:40)
at formatWithOptions (node:internal/util/inspect:2160:10)
at console.value (node:internal/console/constructor:351:14)
at console.warn (node:internal/console/constructor:384:61)
at D:\jeetu\mongodb\index.js:122:27
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
errors: {
age: ValidatorError: Path `age` (-5) is less than minimum allowed value (0).
at validate (D:\jeetu\mongodb\node_modules\mongoose\lib\schemaType.js:1385:13)
at SchemaType.doValidate (D:\jeetu\mongodb\node_modules\mongoose\lib\schemaType.js:1369:7)
at D:\jeetu\mongodb\node_modules\mongoose\lib\document.js:3042:18
at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
properties: [Object],
kind: 'min',
path: 'age',
value: -5,
reason: undefined,
[Symbol(mongoose#validatorError)]: true
}
},
_message: 'User validation failed'
}
User saved
Similar Reads
How to Validate JSON Schema ?
Validating JSON schema ensures that the structure and data types within a JSON document adhere to a predefined schema. This process is crucial for ensuring data consistency and integrity in applications where JSON data is exchanged. ApproachImport the Ajv Library, a popular JSON Schema validator for
2 min read
Specify JSON Schema Validation in MongoDB
MongoDB is a flexible, scalable, and powerful NoSQL database, and one of its notable features is JSON Schema Validation. This feature allows developers to enforce data integrity within MongoDB collections, ensuring that documents inserted into a collection adhere to a specific structure. By specifyi
5 min read
How to Update the First Object in an Array in MongoDB
MongoDB, a popular NoSQL database, offers powerful features for handling complex data structures. One common scenario is updating specific elements within arrays stored in documents. In this guide, we'll focus on updating the first object in an array within a MongoDB document. We'll cover the concep
3 min read
How to Create and Use Enum in Mongoose
Enums in Mongoose play an important role in defining fields that should only accept a limited number of predefined values. They significantly enhance code readability and maintainability by clearly indicating the possible values for a field. In this article, We will explore the concept of enums in M
4 min read
How to define Schema and model in mongoose?
Mongoose is a widely used Object Data Modeling (ODM) library designed for MongoDB in Node.js applications It provides a straightforward way for interacting with MongoDB by offering a schema-based structure. In this article article, we will go through the process of defining schemas and models in Mon
6 min read
How to Join two Schemas in Mongoose?
Mongoose is a popular MongoDB object modeling tool for Node.js that simplifies data manipulation. However, developers often face challenges when trying to join two schemas in Mongoose, as MongoDB, a NoSQL database, does not natively support join operations like SQL databases. In this article, We wil
5 min read
How to Validate Data using joi Module in Node.js ?
Joi module is a popular module for data validation. This module validates the data based on schemas. There are various functions like optional(), required(), min(), max(), etc which make it easy to use and a user-friendly module for validating the data. Introduction to joi It's easy to get started a
3 min read
How to create an id using mongoose in Javascript?
Mongoose is a powerful tool that simplifies MongoDB operations by providing a structured way to define schemas and models. With Mongoose, developers can define relationships between data, apply validation rules, and create reusable query logic. In this article, We will learn about Mongoose, Defining
5 min read
Schema Validation in MongoDB
MongoDB schema validation helps keep your data organized and correct. With MongoDB validation rules, we can set up guidelines for what data can be stored in our database. This makes it easier to ensure that all the information we save is reliable and useful. In this article, We will learn about the
6 min read
How to create new Collection in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This for
1 min read