Home Web Front-end JS Tutorial 3 JavaScript ORMs You Might Not Know

3 JavaScript ORMs You Might Not Know

Feb 19, 2025 am 08:56 AM

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:

1

2

3

4

5

6

7

8

9

10

11

# 获取 knex

$ npm install knex --save

 

# 获取 bookshelf

$ npm install bookshelf --save

 

# 获取其中一个数据库驱动程序

$ npm install pg

$ npm install mysql

$ npm install mariasql

$ npm install sqlite3

Copy after login
Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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'

});

Copy after login
Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

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

  }

});

Copy after login
Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

# 安装 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

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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');

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

var User = sequelize.define('user', {

  firstName: {

    type: Sequelize.STRING,

    field: 'first_name' // `first_name` 列与 User.firstName 匹配

  },

  lastName: {

    type: Sequelize.STRING

  }

}, {

  freezeTableName: true // 模型 tableName (`user`) 将与模型名称相同

});

Copy after login

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:

1

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

Copy after login

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:

1

$ bower install lovefield --save

Copy after login

or npm:

1

$ npm install lovefield --save

Copy after login

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:

1

2

3

4

5

6

7

8

9

// 为“待办事项列表”创建数据库

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']);

Copy after login

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:

1

2

3

4

todoDB.select()

  .from(item)

  .where(item.done.eq(false))

  .exec(); // exec() 返回一个 Promise

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

# 获取 knex

$ npm install knex --save

 

# 获取 bookshelf

$ npm install bookshelf --save

 

# 获取其中一个数据库驱动程序

$ npm install pg

$ npm install mysql

$ npm install mariasql

$ npm install sqlite3

Copy after login
Copy after login

You can also sort it as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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'

});

Copy after login
Copy after login

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

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

  }

});

Copy after login
Copy after login

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

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
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.

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.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles