The latest release of nano-records is out, version 1.1.0 introduces View helpers. The utility of these methods is to more easily query your database.
CouchDB comes with a powerful tool called Views, unfortunately it isn't always the easiest to persist changes directly to your database in the middle of development. A design document is a special document CouchDB uses to formulate clever dynamic responses to queries.
A common practice in application design involves being able to look up a set of results, based on one or two keys on your document. For example you may want all blurbs and creation dates from comments by a specific user, there is a userId
, blurb
, and createdAt
attribute on every comment.
A valid CouchDB view could look like this.
{
"user_comment_blurbs": {
"map": "function (doc) { emit(doc.userId, { blurb: doc.blurb, createdAt: doc.createdAt }); }"
}
}
This would maintain a list of comments sorted and indexed by the userId. You may know how to do this already. Now in nano-records you don't have to anymore.
Without creating a view at all:
db.view.only("userId", ["blurb", "createdAt"], { key: myuserid }, (err, list) => {
if (err)
return;
console.log(list.rows);
});
This would generate an identical view to the one above, but you never had to visit your database. What's more, if you ever lose or corrupt a design it wouldn't matter. The software is smart enough to know whether the view is there and would generate it again.
You can now create simple views simply.
View helpers accept arrays of keys or values, and nested parameters for both. So you are free to get a little more complicated at your leisure.
db.view.only(["userId", "deletedAt"], ["blurb", "createdAt", "author.name"], { key: [myuserid, null] }, (err, list) => {
if (err)
return;
console.log(list.values());
});
This would return all relevant comments without a deletedAt
attribute formatted like so:
{
blurb: "myblurb",
createdAt: "mydate",
author: {
name: "myname"
}
}
Handy.