Sync Documents

A document is a single JSON object, up to 16kb in size. It is best suited to simple use cases, such as basic publish/subscribe or where history synchronization is not a requirement.

Documents can be created, updated, subscribed to and removed via the client JavaScript SDK. Servers wishing to manage these objects can do so via the REST API.

Create and set document data

client.document('user_prefs').then(function(doc) {
  doc.set({
    foregroundColor: "#ffff00",
    backgroundColor: "#ff0000"
  });
});

Using set will overwrite any existing data in a document.

Update data in a document

client.document('user_prefs').then(function(doc) {
  doc.update({foregroundColor: "#ff0000"});
});

Assuming the above user_prefs document contains a foregroundColor and a backgroundColor key, the above update would only modify the foregroundColor key and the backgroundColor key would remain the same.

Mutate data in a document

Use mutate for more fine grained control over updates.

client.document('user_prefs').then(function(doc) {
  doc.mutate(function(remoteData) {
    remoteData.foregroundColor = "#e2e2e2";
    return remoteData;
  });
});

For more details on mutate and conflict resolution read up on Mutation and Conflict Resolution.

Read a document

client.document('user_prefs').then(function(doc) {
  console.log(doc.value);
});

Subscribe to updates on a document

syncClient.document("user_prefs").then(function(doc) {
  doc.on("updated",function(data) {
    console.log(data);
  });
});

Remove a document

syncClient.document("user_prefs").then(function(doc) {
  doc.removeDocument().then(function() {
    console.log('Document removed.');
  });
});

See the JavaScript SDK documentation for a full reference.

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.