search
HomeWeb Front-endJS Tutorial3 JavaScript ORMs You Might Not Know

3 JavaScript ORMs You Might Not Know

Core points

  • This article introduces three JavaScript ORMs that can be used to manage complex data in applications: Bookshelf.js, Sequelize, and Lovefield. Bookshelf.js and Sequelize are designed for Node.js and work well with PostgreSQL, MySQL, MariaDB, SQLite3, and MSSQL. Lovefield is a web application relational database built on IndexedDB, developed by Google.
  • Bookshelf.js and Sequelize allow developers to create one-to-one, one-to-many and many-to-many relationships between tables. They also support transactions, relationships, reads and replication. Although Lovefield does not support raw SQL queries, it mimics SQL syntax and supports ACID transactions, restriction and skip, parameterized queries, etc.
  • Although SQL knowledge is important to developers, JavaScript ORM can simplify work by handling complex data and database interactions. The selection of ORM should be based on the specific requirements of the project, the complexity of the database, and the required functionality.

JavaScript has more than just browser scripts and interactive websites. It can be used almost anywhere:

  • Browser side: No need to be limited to ECMAScript and DOM APIs. CoffeeScript and Dart compiles into pure JavaScript languages ​​that can help you write code faster and better.
  • Server side: The number of Node.js and its many frameworks is increasing, helping front-end developers become full-stack developers.
  • Mobile Apps: Using frameworks like Cordova and Ionic or NativeScript, you can build mobile applications faster without learning other languages ​​like Java or Swift/Objective-C. With these frameworks, you can even share source code between mobile platforms.
  • IoT: SitePoint has published some articles by Patrick Catanzariti, which is very helpful in this regard.

As the complexity of development applications increases, you need tools to help you process all the data stored in the database, whether it is in a database server (such as PostgreSQL), in embedded SQLite for mobile devices, or in In the browser. This is what ORM does. The Java community has Hibernate, PHP developers can use Doctrine ORM, and the JavaScript community also has its own ORM. In this article, I'll cover some JavaScript ORMs that can help you handle complex data in your next application.

Bookshelf.js

Bookshelf.js is a Node.js ORM designed to work well with PostgreSQL, MySQL, MariaDB, and SQLite3. It builds on the Knex SQL query builder and follows some patterns in Backbone.js, such as models and collections and similar naming conventions. If you’ve ever used Backbone, you might get used to Bookshelf very quickly. To install Bookshelf, you need to install Knex and a database driver:

# 获取 knex
$ npm install knex --save

# 获取 bookshelf
$ npm install bookshelf --save

# 获取其中一个数据库驱动程序
$ npm install pg
$ npm install mysql
$ npm install mariasql
$ npm install sqlite3

After the installation is complete (make sure to pass the --save flag so that it is added to the package.json file), you can use it in your Node.js application like this:

var knexInstance = require('knex')({
  client: 'mysql', // 或您正在使用的数据库
  connection: {
    host     : '127.0.0.1',
    user     : 'scott',
    password : 'tiger', // Scott 的猫的名字
    database : 'db_name',
    charset  : 'utf8'
  }
});
// 通过传递 Knex 实例来初始化 Bookshelf
var bookshelf = require('bookshelf')(knexInstance); 

var User = bookshelf.Model.extend({
  tableName: 'users'
});

As you can see, create a Bookshelf object by passing a Knex instance as a parameter. You can then use the Model's extend() method to create a model in your application, just like the User model used for the users table in the example above. Remember that bookshelf is the only instance of Bookshelf that you should use throughout your application. So it's better to make it available everywhere in your application, such as wrapping it in a singleton or putting it in a different file and introducing it if needed. Bookshelf allows you to have one-to-one, one-to-many and many-to-many relationships. In our case, it would be similar to:

var User = bookshelf.Model.extend({
  tableName: 'users',
  posts: function() {
    return this.hasMany(Post);
  }
});

var Post = bookshelf.Model.extend({
  tableName: 'posts',
  user: function() {
    return this.belongsTo(User);
  }
});

If you want to check it out, you can find Bookshelf on GitHub.

Sequelize

Sequelize is another ORM of Node.js and io.js (they end up being merged together). It supports PostgreSQL, MySQL, MariaDB, SQLite and MSSQL, and has powerful transaction support, relationships, read and replica functions. You can install it by running the following command:

# 安装 Sequelize
$ npm install --save sequelize

# 安装数据库驱动程序
$ npm install --save pg pg-hstore

# 对于 mysql 和 mariadb 方言
$ npm install --save mysql 
$ npm install --save sqlite3

# MSSQL
$ npm install --save tedious

Now you can use it as shown in the following example:

var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'|'mariadb'|'sqlite'|'postgres'|'mssql', // 使用其中一个

  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },

  // 仅限 SQLite
  storage: 'path/to/database.sqlite'
});

// 或者您可以简单地使用连接 uri
var sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');

Just like Bookshelf.js, you only need a database connection. After that, you can create a model, for example:

var User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING,
    field: 'first_name' // `first_name` 列与 User.firstName 匹配
  },
  lastName: {
    type: Sequelize.STRING
  }
}, {
  freezeTableName: true // 模型 tableName (`user`) 将与模型名称相同
});

The Sequelize.STRING above matches VARCHAR in SQL. Other data types are Sequelize.INTEGER for INTEGER and Sequelize.BLOB for BLOB (or bytea in Postgres). You can read the full list here. Sequelize allows you to write relationships between tables. For example, if you have a model called Project and another model called Developer and want to assign multiple developers to a project, you can do this:

Project.hasMany(Developer, {as: 'devs'})

This will ensure that the necessary fields are added to each model (in this case project_id in the Developer model). Or, if you feel you can't benefit from the Sequelize API, you can run raw SQL queries. Sequelize is also available on GitHub.

Lovefield

Lovefield is not a real ORM. It is actually a relational database for web applications, built on IndexedDB, developed by Google, and written entirely in JavaScript. It does not support raw SQL queries, but it comes with an API that tries to mimic SQL syntax. You can install it using Bower:

$ bower install lovefield --save

or npm:

$ npm install lovefield --save

After adding it to an HTML file, you can start using it as a front-end relational database. Creating a database and table is simple:

// 为“待办事项列表”创建数据库
var todoDB = lf.schema.create('todo_db', 1);

var item = todoDB.createTable('items')
      .addColumn('id', lf.Type.INTEGER)
      .addColumn('task', lf.Type.STRING)
      .addColumn('deadline', lf.Type.DATE_TIME)
      .addColumn('done', lf.Type.BOOLEAN)
      .addPrimaryKey(['id']);

This code snippet shows how to create a database named todo_db and a table named items, as well as the given column (id as primary key, task, deadline, and completed). At this point, to get a list of all unfinished tasks, the code will be:

todoDB.select()
  .from(item)
  .where(item.done.eq(false))
  .exec(); // exec() 返回一个 Promise

The above code is very similar to SQL, where the same query would be:

# 获取 knex
$ npm install knex --save

# 获取 bookshelf
$ npm install bookshelf --save

# 获取其中一个数据库驱动程序
$ npm install pg
$ npm install mysql
$ npm install mariasql
$ npm install sqlite3

You can also sort it as follows:

var knexInstance = require('knex')({
  client: 'mysql', // 或您正在使用的数据库
  connection: {
    host     : '127.0.0.1',
    user     : 'scott',
    password : 'tiger', // Scott 的猫的名字
    database : 'db_name',
    charset  : 'utf8'
  }
});
// 通过传递 Knex 实例来初始化 Bookshelf
var bookshelf = require('bookshelf')(knexInstance); 

var User = bookshelf.Model.extend({
  tableName: 'users'
});

In addition to these simple queries, Lovefield is able to handle more complex queries, such as joins. If I have references in two table project and developer (referring to table projects and developers respectively), and want to see all projects for a given developer, I would write:

var User = bookshelf.Model.extend({
  tableName: 'users',
  posts: function() {
    return this.hasMany(Post);
  }
});

var Post = bookshelf.Model.extend({
  tableName: 'posts',
  user: function() {
    return this.belongsTo(User);
  }
});

So you can see that Lovefield acts as the SQL layer above IndexedDB. It also supports ACID transactions (atomicity, consistency, isolation, persistence), restriction and skip (useful when paging), parameterized queries, and more. Just like other ORMs, you can download Lovefield from GitHub.

Conclusion

Every developer should have SQL knowledge, but writing SQL queries is boring, especially with so many ORMs. When they make your job easier, why not use them in the beginning? In this article, I’ve covered some of the most important ORMs released so far. Thanks to the examples provided for each ORM, you should now be able to consciously decide which ORM to use and which ORM to suit your needs. What about you? Which JavaScript ORM do you use? Please comment on your choice below.

(The subsequent FAQ section has been omitted because its content is weakly related to the topic of the article and is too long, which will affect the pseudo-original effect. If necessary, you can propose it separately.)

The above is the detailed content of 3 JavaScript ORMs You Might Not Know. 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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),