How to create unique keys in KeystoneJS
you need to change the add method of your model like this:
Word.add({ word: { type: Types.Text, required: true, initial: "New word", index: true, unique: true }});
i tried it and worked for me, notice i added unique:true
i created a keystone project using yeoman's keystone generator, and created a model like yours (you can find it in model/Test.js), then in the admin page when i try to add the same word twice i get:
Error saving changes to Word 569b98f27b5786db1c367b7a:{ [MongoError: E11000 duplicate key error collection: test_unique_field.words index: word_1 dup key: { : "test" }] name: 'MongoError', code: 11000, err: 'E11000 duplicate key error collection: test_unique_field.words index: word_1 dup key: { : "test" }' }
this is the link to the repo if you want to play with it: keystonejs_test_unique
I was only able to enforce the uniqueness by using the mongoose-unique-validator module like so:
var keystone = require('keystone');var Types = keystone.Field.Types;var uniqueValidator = require('mongoose-unique-validator');var Word = new keystone.List('Word', { map: { name: 'word' }});Word.add({ word: { type: Types.Text, index: true, unique: true }});Word.schema.plugin(uniqueValidator);Word.defaultColumns = 'word';Word.register();