PouchDB Create Batch




PouchDB Create Batch

 PouchDB Create Batch

PouchDB Create Batch

  • Batch - It is an array of documents in PouchDB.
  • db.bulkDocs() - It is used to create an array of documents or batch.
  • You'll be able store all the documents that you need to form in PouchDB in an array and pass it to this method as a parameter. This method additionally takes a callback function as a parameter.

Syntax

db.bulkDocs(docs, [options], [callback])  

Create Batch Example

db.bulkDocs() method is used to create multiple documents in PouchDB. Documents must be in JSON Format, a set of key-value pairs separated by comma (,) and enclosed within curly brace({}).

//Requiring the package  
var PouchDB = require('PouchDB');  
//Creating the database object  
var db = new PouchDB('Second_Database');  
//Preparing the documents array  
doc1 = {_id: '001', name: 'Admin', age: 23, Designation: 'Programmer'}  
doc2 = {_id: '002', name: 'nisha', age: 24, Designation: 'Teacher'}  
doc3 = {_id: '003', name: 'Asha', age: 25, Designation: 'Mechanic'}  
docs = [doc1, doc2, doc3]  
//Inserting Documents  
db.bulkDocs(docs, function(err, response) {  
   if (err) {  
      return console.log(err);  
   } else {  
      console.log("Documents created Successfully");  
   }  
});  
  • Save the file name as "Create_Batch.js" within a folder name "PouchDB_Examples". Open the command prompt and execute the JavaScript file using node:
node Create_Batch.js  

Output

 PouchDB Create Batch

PouchDB Create Batch

Create a Batch in Remote Database

We can create a batch in a database which is stored remotely on CouchDB Server. For this purpose, we have to pass the path of the database where we need to create the batch.

Example

  • We have a database named "employees" on the CouchDB Server.

Let's create a batch in "employee" database.

//Requiring the package  
var PouchDB = require('PouchDB');  
//Creating the database object  
var db = new PouchDB('http://localhost:5984/employees');  
//Preparing the documents array  
doc1 = {_id: '001', name: 'remma', age: 24, Designation: 'Teacher'}  
doc2 = {_id: '002', name: 'Ram', age: 25, Designation: 'Designer'}  
doc3 = {_id: '003', name: 'pravin', age: 26, Designation: 'Engineer'}  
docs = [doc1, doc2, doc3]  
//Inserting Documents  
db.bulkDocs(docs, function(err, response) {  
   if (err) {  
      return console.log(err);  
   } else {  
      console.log("Documents (Batch) created Successfully");  
   }  
});  
  • Save the file name as "Create_Batch_Remote.js" within a folder name "PouchDB_Examples". Open the command prompt and execute the JavaScript file using node:
node Create_Batch_Remote.js

Output:

 PouchDB Create Batch

PouchDB Create Batch

Verification

  • You can see the created documents on CouchDB server.
 PouchDB Create Batch

PouchDB Create Batch



Related Searches to PouchDB Create Batch