Model Methods: Insert

Inserting documents into the database collection in MerlinDB.

🪶 MerlinDB's insert method is used to add documents to a collection.

The insert, insertOne, insertMany methods are similar, the only thing that differentiates them is that the 'insertOne' method allows only one document to be inserted into the database, the 'insertMany ' allows multiple documents to be inserted, and 'insert' allows both.

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(
  • "USER-DATABASE"
  • )
  • ;
    6
    7
  • const
  • UserSchema =
  • Schema(
  • {
  •   
    8  
  • name:
  • String
  • ,
    9  
  • age:
  • Number
  • 10
  • }
  • )
  • ;
    11
    12
  • var
  • userModel = merlin
  • .model(
  • "User", UserSchema
  • )
  • ;
    13
    14
  • //userModel.insert(<data(Object|Array)>, <options>);
  • 15
    16
  • //Unique
  • 17userModel
  • .insert(
  • {
  • name:
  • "Savanna",
  • age:
  • 19
  • }
  • )
  • 18
    19
  • //Multiple
  • 20userModel
  • .insert(
  • [
    21  
  • {
  • name:
  • "Savanna",
  • age:
  • 19
  • }
  • ,
    22  
  • {
  • name:
  • "Isabella",
  • age:
  • 26
  • }
  • ,
    23],
  • {
  • ordered:
  • false
  • }
  • )
  • 24
  • //Currently it provides the option to order, default is true;
  • 25
  • //It orders the data in the database and returns the $order in queries
  • 26
  • //By default all data is (ordered: true) ordered by timestamp when entered.
  • 27
    28
  • .then(
  • e =>
  • {
  • 29   console
  • .log(
  • e
  • )
  • ;
    30  
  • //returns
  • 31  
  • {
  • 32      
  • acknowledged:
  • true
  • ,
    33      
  • insertedIds:
  • ["4As32...", "43w24..."],
    34      
  • data:
  • [
    35        
  • {
  • name:
  • "Savanna",
  • age:
  • 19
  • ,
  • id_:
  • "4As32..."
  • }
  • ,
    36        
  • {
  • name:
  • "Isabella",
  • age:
  • 26
  • ,
  • id_:
  • "43w24..."
  • }
  • ,
    37      ]
    38  
  • }
  • 39
  • }
  • )
  • .catch(
  • e =>
  • {
  • 40   console
  • .log(
  • e
  • )
  • ;
    41  
  • //Error message...
  • 42
  • }
  • )