Skip to content

Instantly share code, notes, and snippets.

@sbisbee
Created July 11, 2012 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbisbee/3090838 to your computer and use it in GitHub Desktop.
Save sbisbee/3090838 to your computer and use it in GitHub Desktop.
Quick example of how to overwrite docs without a full GET request to fetch the _rev.
/*
* A real quick example that shows you how to overwrite the entire contents of
* a document without doing a full GET to fetch the document's current _rev.
* This can be dangerous depending on your application because you don't know
* what was written before you and you might be overwriting something
* important.
*
* What it does:
* 1. For the purposes of this test, it issues a PUT to create a document we
* can play with. If it already exists then that's cool.
*
* 2. Issue a HEAD to the document, which gets the _rev in the E-Tag header.
* This is the value we need to include in our new document so that
* CouchDB/Cloudant know we aren't overwriting someone else's work.
*
* 3. Update our document that we want to store.
*
* 4. Issue a PUT of the new data.
*/
var sag = require('sag').server(); //use localhost defaults
var docID = 'someDocID';
sag.setDatabase('quick-test');
//Create the document that we're going to play with.
sag.put({
id: docID,
data: { _id: docID, abc: 123 },
callback: function(resp, succ) {
//only error out if the error we got wasn't a conflict
if(!succ && resp._HTTP.status != 409) {
throw new Error('Was not able to create the doc!');
}
//Now that everything is set up, time to issue our HEAD request
sag.head({
url: docID,
callback: function(resp, succ) {
//The new document that we're going to overwrite the old one with.
var newDoc = {
_id: docID,
foo: 'bar'
};
if(!succ) {
throw new Error('Was not able to HEAD the doc!');
}
newDoc._rev = JSON.parse(resp.headers.etag);
sag.put({
id: docID,
data: newDoc,
callback: function(resp, succ) {
if(!succ) {
throw new Error('Was not able to PUT the doc!');
}
console.log('Done!', resp);
}
});
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment