newUserNameHere
newUserNameHere

Reputation: 17971

Mongo: Create unique text index

Trying to make an index in Mongo that requires the key to be unique and the value to be a text field type.

I create the index:

db.collection.createIndex({id: 'text'}, {unique: true})`

I insert my first record:

db.collection.insert({id: '1'})

I insert a second record with id of 1 (an integer) and expect an error (something like: "id cannot be integer!")

db.collection.insert({id: 1})

How do I ensure that only strings are allowed in the "id" field and that an error is thrown when someone tries to insert an integer?

Upvotes: 0

Views: 296

Answers (1)

Alex Blex
Alex Blex

Reputation: 37018

A tool to ensure correct data types are inserted is SchemaValidation.

In your particular case it must be something like this:

db.runCommand( {
   collMod: "collection",
   validator: { $jsonSchema: {
      bsonType: "object",
      required: [ "id" ],
      properties: {
         id: {
            bsonType: "string",
            description: "must be a string and is required"
         }
      }
   } }
} )

Upvotes: 1

Related Questions