Open In App

How to Create and Validate JSON Schema in MongoDB?

Last Updated : 23 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • Install Mongoose:
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

Next Article

Similar Reads