Schemas: Enum

Defining a restricted set of possible values ​​for a field.

🪶 Enum is a property used to define a restricted set of possible values ​​for a field.

For example, suppose that the country field can only be USA or Brazil, then any value that is not one of them returns an error, let's see:

1
  • import
  • MerlinDB,
  • {
  • Schema
  • }
  • from
  • "@chrisaxxwell/merlin-db";
    2
  • //Or if you are using 'merlindb.max.js' just call 'new MerlinDB()';
  • 3
    4
  • const
  • merlin =
  • new
  • MerlinDB(
  • )
  • ;
    5merlin
  • .connect(
  • "MY-BAR-DATABASE"
  • )
  • ;
    6
    7
  • const
  • DrinkSchema =
  • Schema(
  • {
  •   
    8  
  • drink:
  • {
  • 9      
  • type:
  • String
  • ,
    10      
  • enum:
  • ['sweet-dream', 'blue-sky'],
    11      
  • //Or defining a message
  • 12      
  • enum:
  • {
  • 13        
  • values:
  • [ 'whiskey', 'vodka' ],
    14        
  • message:
  • 'We dont have a
  • {
  • VALUE
  • }
  • in this bar!'
    15      
  • }
  • 16  
  • }
  • 17
  • }
  • )
  • ;
    18
    19
  • var
  • drinkModel = merlin
  • .model(
  • "Drink", DrinkSchema
  • )
  • ;
    20
    21drinkModel
  • .insert(
  • {
  • 22    
  • drink:
  • "Milk"
    23
  • }
  • )
  • .then(
  • e =>
  • {
  • 24  
  • /*  OK...  */
  • 25
  • }
  • )
  • .catch(
  • e =>
  • {
  • 26   console
  • .log(
  • e
  • )
  • ;
    27  
  • //returns We dont have a Milk in this bar!
  • 28
  • }
  • )
  • ;