docs/_includes/api/sync.html
{% include anchor.html edit="true" title="Sync a database" hash="sync" %} {% highlight "js" %} const sync = PouchDB.sync(src, target, [options]) {% endhighlight %} Sync data from src to target and target to src. This is a convenience method for bidirectional data replication. In other words, this code: {% highlight "js" %} PouchDB.replicate('mydb', 'http://localhost:5984/mydb'); PouchDB.replicate('http://localhost:5984/mydb', 'mydb'); {% endhighlight %} is equivalent to this code: {% highlight "js" %} PouchDB.sync('mydb', 'http://localhost:5984/mydb'); {% endhighlight %} ### Options * options.push + options.pull: Allows you to specify separate replication options for the individual replications. Replication options such as filter passed to sync directly will be passed to both replications. Please refer to replicate() for documentation on those options. #### Example Usage: {% highlight "js" %} const sync = PouchDB.sync('mydb', 'http://localhost:5984/mydb', { live: true, retry: true }).on('change', function (info) { // handle change }).on('paused', function (err) { // replication paused (e.g. replication up to date, user went offline) }).on('active', function () { // replicate resumed (e.g. new changes replicating, user went back online) }).on('denied', function (err) { // a document failed to replicate (e.g. due to permissions) }).on('complete', function (info) { // handle complete }).on('error', function (err) { // handle error }); sync.cancel(); // whenever you want to cancel {% endhighlight %} There is also a shorthand for syncing given existing PouchDB objects. This behaves the same as PouchDB.sync(): {% highlight "js" %} db.sync(remoteDB, [options]); {% endhighlight %} It is also possible to combine "one-way" replication and sync for performance reasons. When your PouchDB application starts up it could perform a one-off, one-way replication to completion and then initiate the two-way, continuous retryable sync: {% highlight "js" %} const url = 'http://localhost:5984/mydb'; const opts = { live: true, retry: true }; // do one way, one-off sync from the server until completion db.replicate.from(url).on('complete', function(info) { // then two-way, continuous, retriable sync db.sync(url, opts) .on('change', onSyncChange) .on('paused', onSyncPaused) .on('error', onSyncError); }).on('error', onSyncError); {% endhighlight %} The above technique results in fewer HTTP requests being used and better performance than just using db.sync on its own. #### Example Response: Change events in sync have an extra property direction which refers to the direction the change was going. Its value will either be push or pull. {% highlight "js" %} { direction: 'push', change: { ok: true, start_time: '2015-10-21T15:26:51.151Z', docs_read: 1, docs_written: 1, doc_write_failures: 0, errors: [], last_seq: 1, docs: [[Object] ] } } {% endhighlight %} For any further details, please refer to replicate().