search
HomeWeb Front-endJS TutorialGetting Started with Bookshelf.js

Getting Started with Bookshelf.js

Core points

  • Bookshelf.js is an object-relational mapping (ORM) software for JavaScript (particularly Node.js), which simplifies the process of communicating with a database by allowing developers to use objects in their programming language of choice to interact with the database. .
  • The library provides a simple and intuitive way to perform CRUD (create, read, update, delete) operations and supports a Promise-based interface, which means that functions are called only when the query is successful.
  • As shown in the example of creating a blog JSON API in the article, Bookshelf.js can be used in conjunction with Express.js to build an API, and can be used to encapsulate the underlying database table structure, exposing regular JavaScript objects for querying.

In recent years, JavaScript has surged in popularity. Over the years, people have tried to apply this popular language to the server side many times. One of the most successful attempts was Node.js, which was recommended to the community as a way to write server applications quickly. The selling point of Node is speed, both in terms of performance and development time. With this popularity, the community continues to grow, and the project also benefits from more contributors, resulting in high-quality modules such as Express.js.

So people started to build a complete backend using Node. One of the most important things a backend system should do is communicate with the database effectively. This is where Object Relationship Mapping (ORM) software comes in. Often, developers need to be proficient in the programming language and SQL they are using in order to communicate with databases. ORM simplifies the development process by allowing developers to interact with the database using objects in their programming language of choice. This article introduces ORM and pays special attention to Bookshelf.js ORM.

What is ORM?

Wikipedia defines object relationship mapping as:

A programming technique for converting data between incompatible type systems in object-oriented programming languages. This actually creates a "virtual object database" that can be used internally in the programming language.

In our example, the programming language is JavaScript, and the incompatible system is a relational database system, such as MySQL. This means that the ORM library should allow us to communicate with the database in the same way as interacting with conventional JavaScript objects. There are many ORM libraries in Node.js, and popular libraries include Persistence.js, Sequelize.js, and Bookshelf.js. This article will introduce Bookshelf.js.

Bookshelf.js Example

Database interactions usually revolve around four CRUD operations—create, read, update, and delete. Bookshelf.js provides an intuitive way to perform these operations, for example, create operations like this:

new Post({name: 'New Article'}).save().then(function(model) {
  // ...
});

Suppose Post is a model with the corresponding database table, and name is a property that corresponds to a column in the database table.

Similarly, the read operation is as follows:

new Post({name: 'New Article'}).save().then(function(model) {
  // ...
});

Please note the then call in the code. Bookshelf.js supports a Promise-based interface, in which case this means that the anonymous function passed to then will be called only when the query is successful. A model is a generated JavaScript object that you can use to access properties associated with User. In our example, model.get('gender') returns the user's gender.

Build API with Bookshelf.js and Express.js

For a more complete example, suppose we are delegated to build a blog with the following resources JSON API:

// select * from `user` where `email` = 'user@mail.com'
new User({email: 'user@mail.com'})
  .fetch()
  .then(function(model) {
    console.log(model.get('gender'));
  });

And the client already has the following table:

<code>GET  /api/article
GET  /api/article/:article_id
POST /api/article</code>

First of all, we need to use package.json to set up the Express.js environment:

create table article (
  id int not null primary key,
  title varchar(100) null,
  body text null,
  author varchar(100) null
);

We need the knex query builder because bookshelf depends on it, and we need bluebird to handle the Promise. Our app.js structure is as follows:

{
  "name": "article_api",
  "description": "expose articles via JSON",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "bluebird": "^2.1.3",
    "body-parser": "^1.3.1",
    "express": "4.4.3",
    "mysql": "*",
    "knex": "*",
    "bookshelf": "*"
  }
}

Our MySQL database is called blog. We need to define the article model and bind it to the article table. We will replace // {Our model definition code here}:

// 当应用程序启动时
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Promise = require('bluebird');

var dbConfig = {
  client: 'mysql',
  connection: {
    host: 'localhost',
    user: 'root',
    password: 'your_password',
    database: 'blog',
    charset: 'utf8'
  }
};

var knex = require('knex')(dbConfig);
var bookshelf = require('bookshelf')(knex);

app.set('bookshelf', bookshelf);

var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
};

app.use(allowCrossDomain);
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());

// 解析 application/json
app.use(bodyParser.json());

// 解析 application/vnd.api+json 为 json
app.use(bodyParser.json({type: 'application/vnd.api+json'}));

// 在其他地方,使用 bookshelf 客户端:
var bookshelf = app.get('bookshelf');

// {我们的模型定义代码在这里}

app.listen(3000, function() {
  console.log('Express started at port 3000');
});

No doubt this is everything you need to define a model in Bookshelf.js. We can now use this model to query the database in our API. First, the GET /api/article method should return all articles in the database:

var Article = bookshelf.Model.extend({
  tableName: 'article'
});

fetchAll in Bookshelf.js gets all entries in the database table and catch is performed only if an error occurs (there are more model methods in the document).

Conclusion

Node.js has been developed as a technology and can be used to build web applications and APIs through modules such as Express.js. Bookshelf.js makes interaction with the relational database of Node.js applications easier by encapsulating the underlying database table structure and exposing regular JavaScript objects for querying. This article provides a high-level introduction. The full implementation of the demo project is available on GitHub. (GitHub link should be added here, if it exists)

Bookshelf.js Getting Started FAQ

What is Bookshelf.js and why should I use it?

Bookshelf.js is a JavaScript library that provides a simple and elegant API to interact with SQL databases. It supports transactions, urgent/necked urgent relationship loading, polymorphic associations, and more. The main advantage of using Bookshelf.js is its simplicity and flexibility. It allows you to write less code while doing more things, making your development process faster and more efficient.

How to install Bookshelf.js?

To install Bookshelf.js, you need to install Node.js and npm on your system. After the installation is complete, you can install Bookshelf.js by running the command npm install bookshelf knex sqlite3 --save in the terminal. This will install Bookshelf.js as well as Knex.js (a SQL query builder) and SQLite3 (a lightweight disk-based database).

How to connect Bookshelf.js to my database?

To connect Bookshelf.js to your database, you first need to initialize Knex.js with your database configuration. You then pass this initialized Knex instance to Bookshelf.js. Here is a basic example:

new Post({name: 'New Article'}).save().then(function(model) {
  // ...
});

How to define a model in Bookshelf.js?

In Bookshelf.js, the model is defined by extending the base class Model provided by Bookshelf.js. Here is an example that defines the User model:

// select * from `user` where `email` = 'user@mail.com'
new User({email: 'user@mail.com'})
  .fetch()
  .then(function(model) {
    console.log(model.get('gender'));
  });

How to use Bookshelf.js to extract data from a database?

It is very simple to extract data from a database using Bookshelf.js. You can use the fetch method provided by the model. Here is an example:

<code>GET  /api/article
GET  /api/article/:article_id
POST /api/article</code>

How to save data to a database using Bookshelf.js?

It is also easy to save data to the database using Bookshelf.js. You can use the save method provided by the model. Here is an example:

create table article (
  id int not null primary key,
  title varchar(100) null,
  body text null,
  author varchar(100) null
);

How to use Bookshelf.js to update data in a database?

The data in the database can be updated using the save method. You just need to extract the model first and then call save with the new data. Here is an example:

{
  "name": "article_api",
  "description": "expose articles via JSON",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "bluebird": "^2.1.3",
    "body-parser": "^1.3.1",
    "express": "4.4.3",
    "mysql": "*",
    "knex": "*",
    "bookshelf": "*"
  }
}

How to use Bookshelf.js to delete data from a database?

The data can be deleted from the database using the destroy method provided by the model. Here is an example:

// 当应用程序启动时
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var Promise = require('bluebird');

var dbConfig = {
  client: 'mysql',
  connection: {
    host: 'localhost',
    user: 'root',
    password: 'your_password',
    database: 'blog',
    charset: 'utf8'
  }
};

var knex = require('knex')(dbConfig);
var bookshelf = require('bookshelf')(knex);

app.set('bookshelf', bookshelf);

var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next();
};

app.use(allowCrossDomain);
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());

// 解析 application/json
app.use(bodyParser.json());

// 解析 application/vnd.api+json 为 json
app.use(bodyParser.json({type: 'application/vnd.api+json'}));

// 在其他地方,使用 bookshelf 客户端:
var bookshelf = app.get('bookshelf');

// {我们的模型定义代码在这里}

app.listen(3000, function() {
  console.log('Express started at port 3000');
});

How to handle relationships in Bookshelf.js?

Bookshelf.js provides several ways to deal with relationships between models, such as hasOne, hasMany, belongsTo, and belongsToMany. Here is an example of a User model with multiple Post models:

var Article = bookshelf.Model.extend({
  tableName: 'article'
});

How to handle transactions in Bookshelf.js?

Transactions in Bookshelf.js can be handled using the transaction method provided by Knex.js. Here is an example:

app.get('/api/article', function(req, res) {
  new Article().fetchAll()
    .then(function(articles) {
      res.send(articles.toJSON());
    }).catch(function(error) {
      console.log(error);
      res.send('An error occured');
    });
});

Please note that some of the details in the above code examples may need to be adjusted according to your specific database and environment. In addition, it is recommended to refer to the official documentation of Bookshelf.js for the latest information and more detailed guidance.

The above is the detailed content of Getting Started with Bookshelf.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment