function spSyncData(doc) { var collection = getContext().getCollection(); var collectionLink = collection.getSelfLink(); var response = getContext().getResponse(); var removeFieldTtl = "ttl"; if (!doc) throw new Error("Document is undefined or null."); if (!doc["id"]) throw new Error("The id is undefined or null."); var id = doc["id"]; tryQueryAndUpdate(); function tryQueryAndUpdate(continuation) { var query = { query: "select * from root r where r.id = @id", parameters: [{ name: "@id", value: id }] }; var requestOptions = { continuation: continuation }; var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) { if (err) throw err; if (documents.length > 0) { // If the document is found, update it. // There is no need to check for a continuation token since we are querying for a single document. tryUpdate(documents[0]); } else if (responseOptions.continuation) { // Else if the query came back empty, but with a continuation token; repeat the query w/ the token. // It is highly unlikely for this to happen when performing a query by id; but is included to serve as an example for larger queries. tryQueryAndUpdate(responseOptions.continuation); } else { // Else a document with the given id does not exist.. var isAdded = collection.createDocument(collectionLink, doc, function (err, addDocument, responseOptions) { if (err) throw err; // If we have successfully added the document - return it in the response body. response.setBody(addDocument); }); } }); // If we hit execution bounds - throw an exception. // This is highly unlikely given that this is a query by id; but is included to serve as an example for larger queries. if (!isAccepted) { throw new Error("The stored procedure timed out."); } } // Updates the supplied document according to the update object passed in to the sproc. function tryUpdate(document) { var requestOptions = { etag: document._etag }; var fields, i; delete document[removeFieldTtl]; fields = Object.keys(doc); for (i = 0; i < fields.length; i++) { document[fields[i]] = doc[fields[i]]; } // Update the document. var isAccepted = collection.replaceDocument(document._self, document, requestOptions, function (err, updatedDocument, responseOptions) { if (err) throw err; // If we have successfully updated the document - return it in the response body. response.setBody(updatedDocument); }); // If we hit execution bounds - throw an exception. if (!isAccepted) { throw new Error("The stored procedure timed out."); } } }