PouchDB Create Document




PouchDB Create Document

db.put() method - To create a new document in PouchDB database.

 PouchDB Create Document

PouchDB Create Document

Syntax:

db.put(document, callback)  

Document created in PouchDB database is stored in a variable and pass as a parameter to this method. This method can also takes a callback function as a parameter.

Create Document Example

  • put() - To create a document.
  • The created document must be in JSON format, a set of key-value pairs separated by comma (,) and enclosed within curly braces ({}).
//Requiring the package  
var PouchDB = require('PouchDB');  
//Creating the database object  
var db = new PouchDB('Second_Database');  
//Preparing the document  
doc = {  
   _id : '001',  
   name: 'Ajeet',  
   age : 28,  
   designation : 'Developer'  
   }  
//Inserting Document  
db.put(doc, function(err, response) {  
   if (err) {  
      return console.log(err);  
   } else {  
      console.log("Document created Successfully");  
   }  
});  
  • Save the file named as "Create_Document.js" within a folder name "PouchDB_Examples". Open the command prompt and execute the JavaScript file:
node Create_Document.js  
 PouchDB Create Document

PouchDB Create Document

Insert a Document in Remote Database

  • You can also insert a document in a remotely stored database (CouchDB). You just pass the path of the database where you want to create documents in CouchDB, instead of the database name.

Insert a Document in Remote Database Example

  • We have a database named "employees" on CouchDB.
 PouchDB Create Document

PouchDB Create Document

  • Let's see how to insert a document within the database named "employees" saved on CouchDB server.
//Requiring the package  
var PouchDB = require('PouchDB');  
//Creating the database object  
var db = new PouchDB('http://localhost:5984/employees');  
//Preparing the document  
doc = {  
   _id : '001',  
   name: 'Admin',  
   age : 28,  
   designation : 'Developer'  
   }  
//Inserting Document  
db.put(doc, function(err, response) {  
   if (err) {  
      return console.log(err);  
   } else {  
      console.log("Document created Successfully");  
   }  
});  
  • Save the file named as "Create_Remote_Document.js" within a folder name "PouchDB_Examples". Open the command prompt and execute the JavaScript file using node:
node Create_Remote_Document.js  
 PouchDB Create Document

Verification

Now You can verify that the document is created by visiting the "employees" database on CouchDB Server.

 PouchDB Create Document

PouchDB Create Document

 PouchDB Create Document

PouchDB Create Document



Related Searches to PouchDB Create Document