Menu

Expand
Rate this page:

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 latest JavaScript SDK documentation for a full reference.

Rate this page:

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.

        
        
        

        Thank you for your feedback!

        We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

        Sending your feedback...
        🎉 Thank you for your feedback!
        Something went wrong. Please try again.

        Thanks for your feedback!

        Refer us and get $10 in 3 simple steps!

        Step 1

        Get link

        Get a free personal referral link here

        Step 2

        Give $10

        Your user signs up and upgrade using link

        Step 3

        Get $10

        1,250 free SMSes
        OR 1,000 free voice mins
        OR 12,000 chats
        OR more