cordova - pouchdb 似乎在保存但不保存
问题描述
我正在开发一个科尔多瓦应用程序。由于本地存储空间不足,我开始使用 pouchdb。我将保存在本地存储区的json数据发布到pouchdb。就像创建了一个文档。但该文件不会出现。当我使用 Fetch All Documents 函数时返回 0 行。
create: function (item) {
myApp.db.post(item).then(function (response) {
console.log("Response id " + response.id + " item " + item);
}).catch(function (err) {
console.log(err.name === 'conflict' ? "Conflict occurred - possible duplicate " : "Error " + err);
});
},
loadData: function (callback) {
myApp.db.allDocs({ include_docs: true, attachments: true }, function (err, response) {
if (err) console.log(err);
var rows = response.rows;
for (var i = 0; i < rows.length; i++) {
console.log(rows[i].doc);
alert(JSON.stringify(rows[i].doc));
//var taskItem = myApp.services.tasks.createTaskElem(rows[i].doc);
//if (rows[i].doc.completed)
// myApp.services.tasks.addToCompletedList(taskItem);
//else myApp.services.tasks.addToPendingList(taskItem);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
解决方案
我相信您被 Javascript 的异步特性所欺骗。在处理您的post
命令时,Javascript 继续执行下一个任务……allDocs
并且找不到您的数据,因为它仍在写入 PouchDB。
如果您注意到,每个 PouchDB API 文档示例都有 3 个选项卡,允许您选择 Callback、Promise 或 Async/Await 替代项。我相信你会发现,一旦你掌握了它的诀窍,Async/Await 是迄今为止使用 PouchDB 的最佳方式。
所以,请尝试以下方法,让我知道你的进展情况:
/* Function to instantiate a new random JSON record */
const item = () => {
return {
_id: `Thing_${parseInt(1000*Math.random(), 10)}`,
stuff: ' silly random remark ',
}
};
/* Function to 'put', then retrieve, records from PouchDB */
const dbTest = async () => { // "async" advises JavaScript to expect (otherwise illegal) 'await' statements
console.log(`
Start ...
`);
try {
/* Remember the item ID */
const rndItemId = item();
/* Store the random item in PouchDB */
const response = await myapp.db.put(rndItemId); // Do NOT return until 'put' is complete
/* Log the response from PouchDB */
console.log(`response for <${rndItemId._id}> ....\n${JSON.stringify(response, null, 2)}`);
/* Get back all the random items we 'put' in the Pouch so far */
const result = await myapp.db.allDocs({ // Do NOT return until 'allDocs' is complete
include_docs: true,
attachments: true,
startkey: 'Thing_0',
endkey: 'Thing_999',
});
/* Log the result from PouchDB */
console.log(`result ....\n${JSON.stringify(result, null, 2)}`);
} catch (err) {
console.log(err);
}
console.log(`
... done!
`);
};
/* Call the above function */
dbTest();
/* Call it again */
dbTest();
快速说明:注意使用put
代替post
!请阅读12 个专业提示,以获得更好的 PouchDB 代码。
推荐阅读
- angular - Angular 项目的 l10n 和 i18n 的最佳实践是什么?
- database - 成功和失败的列名
- python - Python:修改存储为字典中的值的变量
- java - 使用 Spring Boot 使用 Apache Camel 调用 wsdl2rest --> 如何修复:转换错误?
- c++ - 如何使用外键删除 Sqlite 中的一行?
- python - GeoPandas - 地图上北部的模糊
- flutter - 创建我的第一个颤振应用程序时遇到问题
- angular - 代码中的角度延迟加载模块(无路由)
- c - 就地向量“abs”警告:操作可能未定义?
- sql-server - 从 SQL Server 导入时,SSIS 包在 VS 中有效,但从文件系统导入时失败(错误 SSIS.Replacement 任务未注册使用)