MongoDB-তে ভ্যালিডেশনের জন্য validator ব্যবহার করুন। MongoDB-তে কালেকশনে ভ্যালিডেশন তৈরি করার কোয়ারি:
> db.createCollection( "demo437" , { ... validator: { $jsonSchema: { ... bsonType: "object", ... required: [ "FirstName", "LastName"], ... properties: { ... FirstName: { ... bsonType: "string", ... description: "This is required" }, ... LastName: { ... bsonType: "string", ... description: "This is required" } ... ... } ... }}}) { "ok" : 1 } একটি কালেকশন তৈরি করি:
> db.demo437.insertOne({"FirstName":"John","LastName":1234}); 2020-03-22T17:49:55.590+0530 E QUERY [js] WriteError: Document failed validation : WriteError({ "index" : 0, "code" : 121, "errmsg" : "Document failed validation", "op" : { "_id" : ObjectId("5e7757ebbbc41e36cc3cae9a"), "FirstName" : "John", "LastName" : 1234 } }) ... > > db.demo437.insertOne({"FirstName":"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5e7757f7bbc41e36cc3cae9b") } > db.demo437.insertOne({"FirstName":9887,"LastName":"Miller"}); 2020-03-22T17:50:29.631+0530 E QUERY [js] WriteError: Document failed validation ... > > > db.demo437.insertOne({"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5e775816bbc41e36cc3cae9d") } find() মেথড দিয়ে সব ডকুমেন্ট দেখান:
> db.demo437.find();
আউটপুট (ভ্যালিড ডকুমেন্টগুলো):
{ "_id" : ObjectId("5e7757f7bbc41e36cc3cae9b"), "FirstName" : "John", "LastName" : "Smith" } { "_id" : ObjectId("5e775816bbc41e36cc3cae9d"), "FirstName" : "David", "LastName" : "Miller" }