Schemas: Unique
Ensuring unique fields in MerlinDB.
🪶 The unique option is used to ensure that the value of a specific field in a schema is unique in the database.
Briefly, if the email field is marked as unique: true, only one email with the same value is allowed.
1 import MerlinDB, { Schema} from "@chrisaxxwell/merlin-db";2 //Or if you are using 'merlindb.min.js' just call 'new MerlinDB()'; 3 4 const merlin = new MerlinDB( ) ;5 merlin.connect( "MY-STORE-DATABASE") ; 6 7 const ClientSchema = Schema({ //Or merlin.Schema(<your-Schema>) 8 name: { type: String , unique: true } , 9 //Or defining a message 10 name: { 11 type: String , 12 unique: [true , "{ VALUE} " already exists database or any message!] 13 } 14 } ) ;15 16 //Your database model looks like this: 17 //model.Clients 18 { id_: "r4RwerF23W3T...", name: "Chris Axxwell" } ,19 { id_: "53fE7Sf...", name: "Jason Statham" } ,20 //...
Now you will try to insert a new customer with the name Chris Axxxell, and this document will not be inserted into the model:
1 var clientModel = merlin.model( "Clients", ClientSchema) ;2 3 try{ 4 await clientModel.insert( { 5 name: "Chris Axxwell" 6 } ) ; 7 }>catch( err) { 8 console.log( err) ; 9 // returns 'Chris Axxwell' name, already exists! 10 }