PouchDB - 讀取文件



您可以使用db.get()方法在PouchDB中讀取/檢索文件內容。

語法

以下是使用PouchDB的db.get()方法的語法。此方法接受文件ID和可選的回撥函式。

db.get(document, callback)

示例

以下是如何使用get()方法在PouchDB中讀取文件內容的示例。

//Requiring the package
var PouchDB = require('PouchDB');

//Creating the database object
var db = new PouchDB('my_database');

//Reading the contents of a Document
db.get('001', function(err, doc) {
   if (err) {
      return console.log(err);
   } else {
      console.log(doc);
   }
});

將以上程式碼儲存到名為Read_Document.js的檔案中。開啟命令提示符並使用node執行JavaScript檔案,如下所示。

C:\PouchDB_Examples >node Read_Document.js

這將讀取本地儲存的名為my_database的資料庫中存在的指定文件的內容。控制檯將顯示以下訊息。

{
   name: 'Raju',
   age: 23,
   designation: 'Designer',
   _id: '001',
   _rev: '1-ba7f6914ac80098e6f63d2bfb0391637'
}

從遠端資料庫讀取文件

您還可以讀取儲存在伺服器(CouchDB)上的遠端資料庫中的文件。

為此,您需要傳遞CouchDB中包含要讀取文件的資料庫的路徑,而不是資料庫名稱。

示例

假設CouchDB伺服器中有一個名為my_database的資料庫。然後,如果您使用URL http://127.0.0.1:5984/_utils/index.html驗證CouchDB中的資料庫列表,您將獲得以下螢幕截圖。

Reading a Document from a Remote Database

點選名為my_database的資料庫,您將看到以下螢幕截圖。在這裡,您可以看到該資料庫包含一個ID為001的文件。

Reading a Document

以下是如何讀取存在於名為my_database的資料庫(儲存在CouchDB伺服器中)中,ID為“001”的文件內容的示例。

//Requiring the package
var PouchDB = require('PouchDB');

//Creating the database object
var db = new PouchDB('https://:5984/my_database');

//Reading the contents of a document
db.get('001', function(err, doc) {
   if (err) {
      return console.log(err);
   } else {
      console.log(doc);
   }
});

將以上程式碼儲存到名為Remote_Read_Document.js的檔案中。開啟命令提示符並使用node執行JavaScript檔案,如下所示。

C:\PouchDB_Examples >node Remote_Read_Document.js

這將讀取儲存在CouchDB中,名為my_database的資料庫中存在的指定文件的內容。控制檯將顯示以下訊息。

{ 
   _id: '001',
   _rev: '3-552920d1ca372986fad7b996ce365f5d',
   name: 'Raju',
   age: 23,
   designation: 'Designer' 
}
廣告