Skip to content

Export and apply Mongo Schema

Joaquín Trillo edited this page Feb 14, 2024 · 1 revision

In this page you will learn how to export the model you have designed as a Mongo Schema and apply it in your MongoDB instance.

  • The model that will be used for this guide will contain a single collection, User.

    user-collection

  • In order to export the Mongo Schema, click 'Export' button in the toolbar. The modal shown below will prompt, where you have to select 'Mongo Schema' option.

    image

  • In this case, the content of the generated file will this. Please copy the content to your clipboard.

    db.createCollection("User", {
      validator: {
        $jsonSchema: {
          bsonType: "object",
          title: "User",
          required: ["_id", "name", "address"],
          properties: {
            "_id": { bsonType: "objectId" },
        "name": { bsonType: "object", title: "name", properties: { "firstName": { bsonType: "string" }, "lastName": { bsonType: "string" }, }, },
        "address": { bsonType: "string" },
        "emails": { bsonType: "array", items: { bsonType: "string" } },
          },
        },
      },
    });
  • Now, let's go to our MongoDB instance. Open MongoDB shell, mongosh, create a new database, paste the contents of your clipboard and press enter. After this, the model designed will be created in the database.

    image

  • In MongoDB Compass we can check the new collection and its schema.

    image

  • Let's create a new document. If the document fails the validation, it will not be created.

    image

  • If the document follows the designed schema, it will be created

image

image

Clone this wiki locally