Database Methods: Creating a new model

Creating a new model for future operations in MerlinDB.

🪶 Creating a model in MerlinDB is very simple, first create a new instance of MerlinDB, then connect to the desired database and call the .createModel() method.

the createModel method accepts two parameters, the first is the model name and the second is the model schema.

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(
  • )
  • ;
    5merlin
  • .connect(
  • "MY-STORE-DATABASE"
  • )
  • ;
    6
    7
  • var
  • cartSchema =
  • Schema(
  • {
  • 8  
  • name:
  • {
  • 9      
  • type:
  • String
  • ,
    10      
  • unique:
  • true
  • 11  
  • }
  • ,
    12  
  • amount:
  • {
  • 13      
  • type:
  • Number
  • ,
    14      
  • required:
  • true
  • ,
    15      
  • min:
  • [
  • 5
  • , 'Min five itens to this product!' ]
    16  
  • }
  • ,
    17
  • }
  • )
  • 18
    19 merlin
  • .createModel(
  • "Cart", cartSchema
  • )
  • .then(
  • e =>
  • {
  • 20   console
  • .log(
  • e
  • )
  • ;
    21  
  • //returns:
  • 22  
  • {
  • 23      
  • "status":
  • 200
  • ,
    24      
  • "message":
  • "Model 'Cart' created!",
    25      
  • "modelInfo":
  • {
  • 26        
  • "name":
  • "Cart",
    27        
  • "indexes":
  • [ "id_", "name", "amount", "$order" ],
    28        
  • "size":
  • "
  • 0
  • bytes",
    29        
  • "records":
  • 0
  • 30      
  • }
  • 31  
  • }
  • 32
    33
  • }
  • )
  • .catch(
  • e =>
  • {
  • 34   console
  • .log(
  • e
  • )
  • ;
    35  
  • //returns 'Cart' model already exists
  • 36
  • }
  • )
  • ;