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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Bring matrix movie effects to your page! This is a cool jQuery plugin based on the famous movie "The Matrix". The plugin simulates the classic green character effects in the movie, and just select a picture and the plugin will convert it into a matrix-style picture filled with numeric characters. Come and try it, it's very interesting! How it works The plugin loads the image onto the canvas and reads the pixel and color values: data = ctx.getImageData(x, y, settings.grainSize, settings.grainSize).data The plugin cleverly reads the rectangular area of the picture and uses jQuery to calculate the average color of each area. Then, use

This article will guide you to create a simple picture carousel using the jQuery library. We will use the bxSlider library, which is built on jQuery and provides many configuration options to set up the carousel. Nowadays, picture carousel has become a must-have feature on the website - one picture is better than a thousand words! After deciding to use the picture carousel, the next question is how to create it. First, you need to collect high-quality, high-resolution pictures. Next, you need to create a picture carousel using HTML and some JavaScript code. There are many libraries on the web that can help you create carousels in different ways. We will use the open source bxSlider library. The bxSlider library supports responsive design, so the carousel built with this library can be adapted to any

Data sets are extremely essential in building API models and various business processes. This is why importing and exporting CSV is an often-needed functionality.In this tutorial, you will learn how to download and import a CSV file within an Angular
