国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

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}:

// 當(dāng)應(yīng)用程序啟動(dòng)時(shí)
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:

// 當(dāng)應(yīng)用程序啟動(dòng)時(shí)
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 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

What is event bubbling and capturing in the DOM? What is event bubbling and capturing in the DOM? Jul 02, 2025 am 01:19 AM

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

What's the Difference Between Java and JavaScript? What's the Difference Between Java and JavaScript? Jun 17, 2025 am 09:17 AM

Java and JavaScript are different programming languages. 1.Java is a statically typed and compiled language, suitable for enterprise applications and large systems. 2. JavaScript is a dynamic type and interpreted language, mainly used for web interaction and front-end development.

See all articles