Table of Contents
What is Bookshelf.js and why should I use it?
How to install Bookshelf.js?
How to connect Bookshelf.js to my database?
How to define a model in Bookshelf.js?
How to use Bookshelf.js to extract data from a database?
How to save data to a database using Bookshelf.js?
How to use Bookshelf.js to update data in a database?
How to use Bookshelf.js to delete data from a database?
How to handle relationships in Bookshelf.js?
How to handle transactions in Bookshelf.js?
Home Web Front-end JS Tutorial Getting Started with Bookshelf.js

Getting Started with Bookshelf.js

Feb 21, 2025 am 10:13 AM

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) {
  // ...
});
Copy after login
Copy after login
Copy after login

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) {
  // ...
});
Copy after login
Copy after login
Copy after login

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'));
  });
Copy after login
Copy after login

And the client already has the following table:

<code>GET  /api/article
GET  /api/article/:article_id
POST /api/article</code>
Copy after login
Copy after login

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
);
Copy after login
Copy after login

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": "*"
  }
}
Copy after login
Copy after login

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');
});
Copy after login
Copy after login

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'
});
Copy after login
Copy after login

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) {
  // ...
});
Copy after login
Copy after login
Copy after login

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'));
  });
Copy after login
Copy after login

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>
Copy after login
Copy after login

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
);
Copy after login
Copy after login

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": "*"
  }
}
Copy after login
Copy after login

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');
});
Copy after login
Copy after login

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'
});
Copy after login
Copy after login

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');
    });
});
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Apr 04, 2025 pm 02:09 PM

Data update problems in zustand asynchronous operations. When using the zustand state management library, you often encounter the problem of data updates that cause asynchronous operations to be untimely. �...

See all articles