Replicating Mongo schema enforcement across multiple database instances

Viewed 29

I'm running a NodeJS application that connects to a Mongo database. I've done the initial development with the MongoClient library. I'm now learning however that without using an ORM like Mongoose, it is becoming increasingly harder to ensure the shape of the data is good. I found a nice thing in the Mongo documentation that indicates I can enforce a schema; one example looking like this:

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "address" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               description: "must be a double if the field exists"
            },
            address: {
               bsonType: "object",
               required: [ "city" ],
               properties: {
                  street: {
                     bsonType: "string",
                     description: "must be a string if the field exists"
                  },
                  city: {
                     bsonType: "string",
                     description: "must be a string and is required"
                  }
               }
            }
         }
      }
   }
})

and it solved my problems except if I were to spin up a new db instance (for instance using a Docker container). Wondering if anyone has any suggestions about how to copy validation across db instances or spin up a new one with it? I will rewrite the application at some point to use Mongoose (or other ORM) but in the mean time I'm looking for a solution to this problem using the validator on a schema.

0 Answers
Related