minimalistic couchdb driver for node.js
nano features:
- minimalistic - there is only a minimum of abstraction between you and couchdb
- pipes - proxy requests from couchdb directly to your end user
- errors - errors are proxied directly from couchdb: if you know couchdb
you already know
nano.
- install npm
npm install nano
- getting started
- tutorials & screencasts
- configuration
- database functions
- nano.db.create(name, [callback])
- nano.db.get(name, [callback])
- nano.db.destroy(name, [callback])
- nano.db.list([callback])
- nano.db.compact(name, [designname], [callback])
- nano.db.replicate(source, target, [opts], [callback])
- nano.db.changes(name, [params], [callback])
- nano.db.follow(name, [params], [callback])
- nano.db.info([callback])
- nano.use(name)
- nano.request(opts, [callback])
- nano.config
- nano.updates([params], [callback])
- nano.followUpdates([params], [callback])
- document functions
- db.insert(doc, [params], [callback])
- db.destroy(docname, rev, [callback])
- db.get(docname, [params], [callback])
- db.head(docname, [callback])
- db.copy(src_doc, dest_doc, opts, [callback])
- db.bulk(docs, [params], [callback])
- db.list([params], [callback])
- db.fetch(docnames, [params], [callback])
- db.fetchRevs(docnames, [params], [callback])
- multipart functions
- attachments functions
- views and design functions
- using cookie authentication
- advanced features
- tests
to use nano you need to connect it to your couchdb install, to do that:
var nano = require('nano')('http://localhost:5984');to create a new database:
nano.db.create('alice');and to use it:
var alice = nano.db.use('alice');in this examples we didn't specify a callback function, the absence of a
callback means "do this, ignore what happens".
in nano the callback function receives always three arguments:
err- the error, if anybody- the http response body from couchdb, if no error. json parsed body, binary for non json responsesheader- the http response header from couchdb, if no error
a simple but complete example using callbacks is:
var nano = require('nano')('http://localhost:5984');
// clean up the database we created previously
nano.db.destroy('alice', function() {
// create a new database
nano.db.create('alice', function() {
// specify the database we are going to use
var alice = nano.use('alice');
// and insert a document in it
alice.insert({ crazy: true }, 'rabbit', function(err, body, header) {
if (err) {
console.log('[alice.insert] ', err.message);
return;
}
console.log('you have inserted the rabbit.')
console.log(body);
});
});
});if you run this example(after starting couchdb) you will see:
you have inserted the rabbit.
{ ok: true,
id: 'rabbit',
rev: '1-6e4cb465d49c0368ac3946506d26335d' }
you can also see your document in futon.
configuring nano to use your database server is as simple as:
var nano = require('nano')('http://localhost:5984')
, db = nano.use('foo')
;however if you don't need to instrument database objects you can simply:
// nano parses the url and knows this is a database
var db = require('nano')('http://localhost:5984/foo');you can also pass options to the require:
// nano parses the url and knows this is a database
var db = require('nano')('http://localhost:5984/foo');to specify further configuration options you can pass an object literal instead:
// nano parses the url and knows this is a database
var db = require('nano')(
{ "url" : "http://localhost:5984/foo"
, "requestDefaults" : { "proxy" : "http://someproxy" }
, "log" : function (id, args) {
console.log(id, args);
}
});Please check request for more information on the defaults. They support features like cookie jar, proxies, ssl, etc.
You can tell nano to not parse the url (maybe the server is behind a proxy, is accessed through a rewrite rule or other):
// nano does not parse the url and return the server api
// "http://localhost:5984/prefix" is the CouchDB server root
var couch = require('nano')(
{ "url" : "http://localhost:5984/prefix"
"parseUrl" : false
});
var db = couch.use('foo');a very important configuration parameter if you have a high traffic website and are using nano is setting up the pool.size. by default, the node.js http global agent (client) has a certain size of active connections that can run simultaneously, while others are kept in a queue. pooling can be disabled by setting the agent property in requestDefaults to false, or adjust the global pool size using:
http.globalAgent.maxSockets = 20;you can also increase the size in your calling context using requestDefaults if this is problematic. refer to the request documentation and examples for further clarification.
here's an example explicitly using the keep alive agent (installed using npm install agentkeepalive), especially useful to limit your open sockets when doing high-volume access to couchdb on localhost:
var agentkeepalive = require('agentkeepalive');
var myagent = new agentkeepalive({
maxSockets: 50
, maxKeepAliveRequests: 0
, maxKeepAliveTime: 30000
});
var db = require('nano')(
{ "url" : "http://localhost:5984/foo"
, "requestDefaults" : { "agent" : myagent }
});creates a couchdb database with the given name.
nano.db.create('alice', function(err, body) {
if (!err) {
console.log('database alice created!');
}
});get informations about name.
nano.db.get('alice', function(err, body) {
if (!err) {
console.log(body);
}
});destroys name.
nano.db.destroy('alice');even though this examples looks sync it is an async function.
lists all the databases in couchdb
nano.db.list(function(err, body) {
// body is an array
body.forEach(function(db) {
console.log(db);
});
});compacts name, if designname is specified also compacts its
views.
replicates source on target with options opts. target
has to exist, add create_target:true to opts to create it prior to
replication.
nano.db.replicate('alice', 'http://admin:password@otherhost.com:5984/alice',
{ create_target:true }, function(err, body) {
if (!err)
console.log(body);
});asks for the changes feed of name, params contains additions
to the query string.
nano.db.changes('alice', function(err, body) {
if (!err) {
console.log(body);
}
});Uses Follow to create a solid changes feed. please consult follow documentation for more information as this is a very complete API on it's own.
var feed = db.follow({since: "now"});
feed.on('change', function (change) {
console.log("change: ", change);
});
feed.follow();
process.nextTick(function () {
db.insert({"bar": "baz"}, "bar");
});gets database information.
nano.db.info(function(err, body) { if (!err) { console.log('got database info'', body); } });
creates a scope where you operate inside name.
var alice = nano.use('alice');
alice.insert({ crazy: true }, 'rabbit', function(err, body) {
// do something
});alias for nano.use
alias for nano.use
alias for nano.use
makes a request to couchdb, the available opts are:
opts.db– the database nameopts.method– the http method, defaults togetopts.path– the full path of the request, overridesopts.docandopts.attopts.doc– the document nameopts.att– the attachment nameopts.qs– query string parameters, appended after any existingopts.path,opts.doc, oropts.attopts.content_type– the content type of the request, default tojsonopts.headers– additional http headers, overrides existing onesopts.body– the document or attachment bodyopts.encoding– the encoding for attachmentsopts.multipart– array of objects for multipart request
alias for nano.request
alias for nano.request
_
/ '_) WAT U SAY!
_.----._/ /
/ /
_/ ( | ( |
/__.-|_|--|_l
an object containing the nano configurations, possible keys are:
url- the couchdb urldb- the database name
listen to db updates, the available params are:
params.feed– Type of feed. Can be one oflongpoll: Closes the connection after the first event.continuous: Send a line of JSON per event. Keeps the socket open until timeout.eventsource: Like, continuous, but sends the events in EventSource format.params.timeout– Number of seconds until CouchDB closes the connection. Default is 60.params.heartbeat– Whether CouchDB will send a newline character (\n) on timeout. Default is true.
** changed in version 6 **
Use Follow to create a solid
_db_updates feed.
Please consult follow documentation for more information as this is a very complete api on it's own
var feed = nano.followUpdates({since: "now"});
feed.on('change', function (change) {
console.log("change: ", change);
});
feed.follow();
process.nextTick(function () {
nano.db.create('alice');
});inserts doc in the database with optional params. if params is a string, its assumed as the intended document name. if params is an object, its passed as query string parameters and docName is checked for defining the document name.
var alice = nano.use('alice');
alice.insert({ crazy: true }, 'rabbit', function(err, body) {
if (!err)
console.log(body);
});The insert function can also be used with the method signature db.insert(doc,[callback]), where the doc contains the _id field e.g.
var alice = nano.use('alice')
alice.insert({ _id: 'myid', crazy: true }, function(err, body) {
if (!err)
console.log(body)
})and also used to update an existing document, by including the _rev token in the document being saved:
var alice = nano.use('alice')
alice.insert({ _id: 'myid', _rev: '1-23202479633c2b380f79507a776743d5', crazy: false }, function(err, body) {
if (!err)
console.log(body)
})removes revision rev of docname from couchdb.
alice.destroy('rabbit', '3-66c01cdf99e84c83a9b3fe65b88db8c0', function(err, body) {
if (!err)
console.log(body);
});gets docname from the database with optional query string
additions params.
alice.get('rabbit', { revs_info: true }, function(err, body) {
if (!err)
console.log(body);
});
