如何在本地的PouchDB数据库中导入/导出数据?
我需要保存我的本地数据库并在不同的平台上打开它。
服务器端没有CouchDB。
这些功能由了不起的@nolanlawson编写。你不仅可以导入/导出,还可以做各种事情。真是太棒了。
PouchDB Replication Stream https://github.com/nolanlawson/pouchdb-replication-stream
PouchDB/CouchDB复制的ReadableStreams和WritableStreams。 基本上,您只需将流附加在一起即可复制两个数据库。这有很多用途:将数据库转储到文件中,然后将同一个文件加载到另一个数据库中。通过将CouchDB的内容转储到HTTP端点,然后在浏览器中加载到PouchDB中,可以快速进行初始复制。通过web套接字进行复制?通过蓝牙?通过NFC?为什么不呢?由于复制流只是JSON纯文本,因此可以将其通过任何传输机制发送。定期备份您的数据库。
以及使用PouchDB.load导入: https://github.com/nolanlawson/pouchdb-load
客户端工具,用于从CouchDB/PouchDB数据库加载转储。 要转储,请查看pouchdb-dump-cli以从命令行转储,或者在Node.js应用程序内部使用pouchdb-replication-stream进行转储。此方法通常比标准复制快得多,因为它使用较少的HTTP请求。因此,这是一种快速加载数据库初始状态的好方法。
db.allDocs({include_docs: true, attachments: true}).then(JSON.stringify);
最简单的解决方案是使用批量操作,就像 @mrded 提到的那样:
<button onClick={handleExport}>Export</button>
<input type="file" onChange={handleImport}/>
function handleExport () {
db.allDocs({include_docs: true}, (error, doc) => {
if (error) console.error(error);
else download(
JSON.stringify(doc.rows.map(({doc}) => doc)),
'tracker.db',
'text/plain'
);
});
}
function handleImport ({target: {files: [file]}}) {
if (file) {
const reader = new FileReader();
reader.onload = ({target: {result}}) => {
db.bulkDocs(
JSON.parse(result),
{new_edits: false}, // not change revision
(...args) => console.log('DONE', args)
);
};
reader.readAsText(file);
}
}
还要检查下载函数。