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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version