| {% include anchor.html edit="true" title="Sync a database" hash="sync" %} | |
| {% highlight js %} | |
| var 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](api.html#replication) for the individual replications. | |
| Replication options such as `filter` passed to sync directly will be passed to both replications. Please refer to [replicate()](api.html#replication) for documentation on those options. | |
| #### Example Usage: | |
| {% highlight js %} | |
| var 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 %} | |
| #### 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()](api.html#replication). | |