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);
How to Create and Validate JSON Schema in MongoDB?
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:
Table of Content
- Creating JSON Schema
- Using MongoDB Shell
- Using Mongoose