MongoDB Export - borkdominik/bigER GitHub Wiki

The MongoDB export selects a database using the ER model's name, or creates a new one if it does not exist. For each entity and relationship in the ER model, a new collection is created. The collections further specify a JSON schema that can be used for validation, with attributes mapped to properties and their datatypes used as bsonType. See the official JSON Schema documentation and the MongoDB documentation on JSON Schema Validation for more information.

Example

ER Model

erdiagram BasicExample

entity E1 {
    a1: int key
    a2: string
}
entity E2 {
    a3: int key
    a4: double
}
relationship R1 {
    E1[1] -> E2[N] 
}

MongoDB Export

use("BasicExample");

db.createCollection("E1", {
    validator: {
        $jsonSchema: {
	    bsonType: "object",
	    title: "E1 (Entity) Object Validation",
	    required: [ "a1" ],
	    properties: {
                a1: {
		    bsonType: "int"
	    },
                a2: {
		    bsonType: "string"
		}
	    }
	}
    }
});
db.createCollection("E2", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
	    title: "E2 (Entity) Object Validation",
	    required: [ "a3" ],
	    properties: {
	        a3: {
		    bsonType: "int"
	        },
		a4: {
		    bsonType: "double"
		}
	    }
	}
    }
});
db.createCollection("R1", {
    validator: {
	$jsonSchema: {
	    bsonType: "object",
	    title: "R1 (Relationship) Object Validation",
	    required: [ "a1", "a3" ],
	    properties: {
		a1: {
		    bsonType: "int",
		},
		a3: {
		    bsonType: "int",
		},
	    }
	}
    }
});

After executing the generated code on a running MongoDB instance, documents can be added to the collections using, e.g., MongoDB Shell mongosh or the MongoDB VS Code extension. When inserting new documents, the properties are validated against the specified JSON schema as demonstrated below:

Valid

db.getCollection('E1').insertOne({
    a1: 123,
    a2: "Text"
});

Invalid

db.getCollection('E1').insertOne({
    a1: 123,
    a2: 123
});

Invalid, since the property a2 is of type number and not string as specified in the exported schema above.