Tuesday, 8 June 2021

MongoDB: Validate documents while inserting (or) updating

In this post, I am going to explain how to validate documents in MongoDB.

 

There are two ways to add validation logic to the collection.

a.   specify schema at the time of collection creation

b.   Add schema to the existing collection

 

Specify schema at the time of collection creation

Let’s create an employee collection and define the schema for it.


db.createCollection('employee', {
	
	validator : {
		$jsonSchema : {
			bsonType: 'object',
			required: ['empId', 'firstName', 'lastName'],

			properties: {
				empId : {
					bsonType : 'int',
					description: 'empId must be an integer and mandatory property'
				},
				firstName : {
					bsonType: 'string',
					description: 'firstName must be a string and mandatory property'
				},
				lastName : {
					bsonType: 'string',
					description: 'lastName must be a string and mandatory property'
				},
				hobbies : {
					bsonType : 'array',
					description: 'Hobbies of user',
					items: {
						bsonType: 'int'
					}
				},
				projects : {
					bsonType : 'array',
					description: 'Hobbies of user',
					required: ['pjtName', 'pjtId'],
					items: {
						bsonType: 'object',
						properties : {
							pjtName : {
								bsonType: 'string',
								description: 'pjtName must be a string and mandatory property'
							},
							pjtId : {
								bsonType: 'int',
								description: 'pjtId must be a string and mandatory property'
							}
						}
					}
				}
			}

		}
	}
});

 

Let’s try to insert some invalid information

Employee with only empId and firstName.

> db.employee.insert({"empId": 1, "firstName": "Krishna"})
WriteResult({
	"nInserted" : 0,
	"writeError" : {
		"code" : 121,
		"errmsg" : "Document failed validation"
	}
})
>
>
> db.employee.insert({"empId": NumberInt(1), "firstName": "Krishna"})
WriteResult({
	"nInserted" : 0,
	"writeError" : {
		"code" : 121,
		"errmsg" : "Document failed validation"
	}
})

 

Employee with empId, firstName and lastName properties

 

> db.employee.insert({"empId": NumberInt(1), "firstName": "Krishna", "lastName" : "Gurram"})
WriteResult({ "nInserted" : 1 })

  Let’s try to add project property and invalid information to project object

 

> db.employee.insert({"empId": NumberInt(2), "firstName": "Keerthi", "lastName" : "Shetty", "projects": [{"pjtName": "CPCS", "pjtId": 123}]})
WriteResult({
	"nInserted" : 0,
	"writeError" : {
		"code" : 121,
		"errmsg" : "Document failed validation"
	}
})

 

In the above example the property "pjtId" should be of type NumberInt. Let’s correct and insert the data.

> db.employee.insert({"empId": NumberInt(2), "firstName": "Keerthi", "lastName" : "Shetty", "projects": [{"pjtName": "CPCS", "pjtId": NumberInt(123)}]})
WriteResult({ "nInserted" : 1 })

 

Let’s print all the documents of employee collection.

> db.employee.find().pretty()
{
	"_id" : ObjectId("60bf985412681e44943c7974"),
	"empId" : 1,
	"firstName" : "Krishna",
	"lastName" : "Gurram"
}
{
	"_id" : ObjectId("60bf997a12681e44943c797a"),
	"empId" : 2,
	"firstName" : "Keerthi",
	"lastName" : "Shetty",
	"projects" : [
		{
			"pjtName" : "CPCS",
			"pjtId" : 123
		}
	]
}

 

Can I add any additional properties other than schema defined ones?

Yes

 

For example, below snipped add age property to the document.

> db.employee.insert({"empId": NumberInt(3), "firstName": "Gopi", "lastName" : "Battu", "age": 33})
WriteResult({ "nInserted" : 1 })

 

Let’s print all the documents in employee collection.

> db.employee.find().pretty()
{
	"_id" : ObjectId("60bf9a4c12681e44943c797d"),
	"empId" : 1,
	"firstName" : "Krishna",
	"lastName" : "Gurram"
}
{
	"_id" : ObjectId("60bf9a6312681e44943c797f"),
	"empId" : 2,
	"firstName" : "Keerthi",
	"lastName" : "Shetty",
	"projects" : [
		{
			"pjtName" : "CPCS",
			"pjtId" : 123
		}
	]
}
{
	"_id" : ObjectId("60bf9af812681e44943c7981"),
	"empId" : 3,
	"firstName" : "Gopi",
	"lastName" : "Battu",
	"age" : 33
}

 

 

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment