Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import/export database from PouchDB

How to import/export database from local PouchDB database? I need save my local database and open it in different platform. There is no CouchDB on server side.

like image 601
pZCZ Avatar asked May 14 '16 17:05

pZCZ


3 Answers

There are features coded by the amazing @nolanlawson. Not only you can import/export it, you can do all sorts of things with it. Just awesome.

PouchDB Replication Stream https://github.com/nolanlawson/pouchdb-replication-stream

ReadableStreams and WritableStreams for PouchDB/CouchDB replication. Basically, you can replicate two databases by just attaching the streams together. This has many uses: Dump a database to a file, and then load that same file into another database. Do a quick initial replication by dumping the contents of a CouchDB to an HTTP endpoint, which is then loaded into a PouchDB in the browser. Replicate over web sockets? Over bluetooth? Over NFC? Why not? Since the replication stream is just JSON plaintext, you can send it over any transport mechanism. Periodically backup your database.

And PouchDB.load to import: https://github.com/nolanlawson/pouchdb-load

Client-side tools for loading a dump from a CouchDB/PouchDB database. For dumping, check out pouchdb-dump-cli to dump from the command line, or pouchdb-replication-stream to dump from within your Node.js application. This method is typically much faster than standard replication, because it uses fewer HTTP requests. So it's a great way to quickly load an initial state for your database.

like image 176
Matías Avatar answered Nov 16 '22 11:11

Matías


To export, why don't you just load all docs and save them into a file?

db.allDocs({include_docs: true, attachments: true}).then(JSON.stringify);
like image 35
mrded Avatar answered Nov 16 '22 10:11

mrded


The simplest solution, as @mrded said, is to use batch operations:

<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);
  }
}

Also check the download function.

like image 2
Igor Sukharev Avatar answered Nov 16 '22 09:11

Igor Sukharev