Has anyone used the jsonSchema validation in Mongo?

Has anyone used the jsonSchema validator with the mongodb package? I’m hoping to implement something like what is demonstrated in the docs:

I’ve tried something like this:

Mongo.command(mongo_pid(), [createCollection: coll])

after looking over the mongodb source code, but so far, I’ve only succeeded in getting this message:

%Mongo.Error{code: 59, host: nil, message: "command failed: no such command: 'createCollection'"}

Figured it out. Anyone who needs to define $jsonSchema validation on their Mongo collections can issue a command like the following:

# Create the collection by inserting a record 
Mongo.insert_one(mongo_pid(), "phones", %{"phone" => "888-555-1212", "name" => "Example"})

# Modify the collection
cmd = [
        collMod: "phones",
        validator: [
            json_schema: %{
              bson_type: "object",
              required: ["phone"]
Mongo.command(mongo_pid(), cmd)

Remember: you can only use collMod on an existing collection! Insert a document there (or maybe create an index?) to get the collection created so you can modify it.

Note: the above code uses the mongo_pid() function to retrieve the proper process.

1 Like

command name is create not createCollection source

try this instead

 iex(1)> Mongo.command(:mongo, %{create: "users"})
{:ok, %{"ok" => 1.0}}
1 Like