如何从 pouchdb 检索 json 数据

how to retrieve json data from pouchdb

我正在尝试 return 来自 pouchdb 的特定 Json 数据,如果数据存在,我想显示一些 activity。但不知何故,我无法这样做。 我的代码

var PouchDB = require('PouchDB'); 
//Creating the database object 
var db = new PouchDB('my_database');
 //Reading the contents of a Document 
var res = db.get('001', function(err, doc)
  if (err)
 {
 return console.log(err);
 } 
else
 { 
var data = JSON.stringify(res)
return console.log(doc);
 } });

我得到的结果是:{} 空集

您的示例中的问题是您使用的是带有回调和 Promises 的 PouchDB。您需要使用回调或承诺。这是您应该使用的代码段。我用回调和承诺做了一个例子。

如您所见,Promises 让您的工作流程更加简洁。

此外,出于安全原因,该示例不会 运行 直接在 Whosebug 中。这是一个外部工作示例:http://jsbin.com/javipoguqe/1/edit?js,console

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

//Callback example 

db.get('001', function(err, doc) {
  if (err) {
    return console.log(err);
  } else {
    var data = JSON.stringify(res)
    return console.log(doc);
  }
});

//Promise example

var promise = db.get('001');
promise.then(function(res) {
  console.log(JSON.stringify(res));
}).catch(function(err) {
  console.log(JSON.stringify(err));
});


//Example to show advantages of promises

db.put({
  '_id': "001",
  name: "newdoc"
}).then(function(res) {
  return db.get('001');
}).then(function(res) {
  console.log("Document was added and retrieved");
}).catch(function(err) {
  console.log(JSON.stringify(err));
});
<script src="https://cdn.jsdelivr.net/pouchdb/latest/pouchdb.min.js"></script>