Getting Started with Bookshelf.js

In the last three years we have seen a spike in JavaScript’s popularity. Over the years, there have been multiple attempts at taking the popular language to the server. The most prevailing of these attempts has been Node.js, which was presented to the community as a quick way of writing server applications. The selling point for Node was speed, both in terms of performance and in development time. With this kind of popularity the community grew and the project benefited from more contributors, resulting in high quality modules like Express.js.

As a result people started building complete back ends using Node. One of the most important things a back end system should do is communicate with databases efficiently. This is where Object-Relational Mapping, or ORM, software comes in. Normally, developers need to be good in both the programming language they are using and SQL in order to communicate with databases. ORMs make life easier by allowing developers to interact with databases within the programming language of their choice using objects. This article introduces ORMs, and looks specifically at the Bookshelf.js ORM.

What is an ORM?

Wikipedia defines Object-Relational Mapping as:

a programming technique for converting data between incompatible type
systems in object-oriented programming languages. This creates, in
effect, a “virtual object database” that can be used from within the
programming language

Now in our case, the programming language is JavaScript, and the incompatible system is a relational database system such as MySQL. This means that an ORM Library should allow us to communicate with the database the same way we interact with regular JavaScript objects. There are many ORM libraries that exist for Node.js, the popular ones being Persistence.js, Sequelize.js, and Bookshelf.js. This article will introduce Bookshelf.js.

Bookshelf.js Examples

Database interactions are typically centered around the four CRUD operations – create, read, update, and delete. Bookshelf.js provides an intuitive way of doing this, for example, this what a create operation would look like: