Creating a document in CouchDB using Node.js and Cradle
The Cradle module provides the save
method to save a new document to the database. You pass the document to save and a callback to invoke when the operation completes or fails.
How to do it...
Here's how to save a simple record using save
:
var item = { call: 'kf6gpe-7', lat: 37, lng: -122 }; db.save(item, function (error, result) { if (error) { console.log(error); // Handle error } else { var id = result.id; var rev = result.rev; } });
How it works…
The save method returns a JavaScript object to your callback with fields for the newly created document IDs and an internal revision number, along with a field titled ok, which should be true. As you'll see in the recipe titled Updating a Record in CouchDB with Node.js, you need both the revision of a document you store and the ID in order to update it; otherwise, you end up creating a new document or receiving a failure to save the record. An example result...