PouchDB Add Attachment
The putAttachment() method is used to add a binary object to a document in PouchDB. To use this method, you have to pass the document id, attachment id, MIME type along with the attachment. This method also accepts an optional callback function.
Syntax:
Blob or buffer object is used to prepare attachment with documents. Blob is used while working with browser and buffer is used while working with Node.js.
Here we are using Node.js console so we will use buffer object.
Add Attachment Example
Let’s take an example to create a document with an attachent in a newly created database “New_Database”.
Save the above code in a file named “Add_Attachment.js” within a folder name “PouchDB_Examples”. Open the command prompt and execute the JavaScript file using node:
Output:
The above example will create an empty document adding an attachment to the database named “New_Database” which is stored in PouchDB.
Verification
Use the following code to verify if the attachment is added.
Save the above code in a file named “Read_Doc.js” within a folder name “PouchDB_Examples”. Open the command prompt and execute the JavaScript file using node:
Output:
Add attachment to an existing document
We have a document in database named “Last_Database” with id “002”. You can see the value of the document:
Now add an attachment to this document using its _rev value.
Example:
Save the above code in a file named “Add_Attachment2.js” within a folder name “PouchDB_Examples”. Open the command prompt and execute the JavaScript file using node:
Output:
Verification
You can verify the added attachment by using the read command:
Add Attachment to a Remote Database
You can also add an attachment to a remotely stored server (CouchDB). You just have to pass the path to the database in CouchDB, which contains the document where you want to add your attachment.
Example
We have a database name “employees” stored on the CouchDB server.
There is one document in the database, having id 001.
Add an attachment to the document 001 stored in a database named “employees” which is stored in the CouchDB server.
Save the above code in a file named “Add_Remote_Attachment.js” within a folder name “PouchDB_Examples”. Open the command prompt and execute the JavaScript file using node:
Output:
Verification
Go to CouchDB server and you can see that attachment is added with the document.