Inserting new document from Realm function not adhere to document schema

I have the following activity.json schema:

{
  "title": "Activity",
  "bsonType": "object",
  "properties": {
    "_id": {
      "bsonType": "objectId"
    },
    "name": {
      "bsonType": "string"
    },
    "description": {
      "bsonType": "string"
    },
    "categories": {
      "bsonType": "array",
      "items": {
        "bsonType": "string"
      },
      "minItems": 1,
      "uniqueItems": true
    },
    "location": {
      "bsonType": "object",
      "properties": {
        "latitude": {
          "bsonType": "double"
        },
        "longitude": {
          "bsonType": "double"
        }
      },
      "required": [
        "latitude",
        "longitude"
      ]
    }
  },
  "required": [
    "_id",
    "name",
    "categories",
    "location"
  ]
}

I also have the following insertOneActivity.js Realm function:

exports = ({ name, description, categories: [...category], location: { latitude, longitude } }) => {
  const mongodb = context.services.get("mongodb-atlas");
  const activityCollection = mongodb.db("crowdfinder").collection("activity");
  const query = {
    // "name": name, // <--- commented out
    "description": description,
    "categories": category,
    "location": {
      "latitude": latitude,
      "longitude": longitude
    }
  };

  // console.log(`${name}, ${description}, ${category}, ${latitude}, ${longitude}\n`);
  try {
    const result = activityCollection.insertOne(query);
    console.log(`Document inserted successfully: ${result}`)
    return result;
  } catch(err) {
    console.error(`Failed to insert document: ${err}`);
  }
}

I tried to run insertOneActivity function with this command:

realm-cli function run --name insertOneActivity --args "{\"name\": \"Act 1\", \"description\": \"Act 1 desc
\", \"categories\": [\"test\"], \"location\": {\"latitude\": 1, \"longitude\": 2}}"

The document should not have the name field, and therefore it should not be accepted/inserted to the Atlas DB because of name is defined in required array in the object schema.

However, the command in fact insert a new document successfully.
image

Am I missing something here?

Note that the first document is the “correct” one with name field. What I am asking is why the second document is allowed to be inserted.

Hi Afiq, welcome to the forums! :wave:

The issue here is that your function is not running as a specific user - that is, it’s a system function that totally bypasses your rules & schema. Realm will enforce the schema if you run it as a specific user by passing their user ID in the --user argument.

This wouldn’t be an issue if you were to call the function from a Realm SDK because they require a user to be logged in. However, the CLI is authenticated with a Project Owner API key so it has access to the system context in the same way you would if you were to use the Realm UI instead.

1 Like