Nodejs ORM框架objection的使用
Nodejs ORM框架objection的使用
Objection.js 是一个强大的 Node.js ORM(对象关系映射)库,它基于 Knex.js 查询构建器。Objection.js 旨在提供简单、可组合和易于使用的 API,同时保持高性能。
以下是使用 Objection.js 的基本步骤:
1. 安装依赖
首先,你需要安装 objection
和 knex
以及你的数据库驱动(例如 PostgreSQL 的 pg
或 MySQL 的 mysql2
)。
npm install objection knex pg # 对于 PostgreSQL
# 或者
npm install objection knex mysql2 # 对于 MySQL
2. 配置 Knex
创建一个 Knex 配置文件来连接到数据库。
// knexfile.js
module.exports = {
development: {
client: 'pg', // 或者 'mysql'
connection: {
host: '127.0.0.1',
user: 'your_database_user',
password: 'password',
database: 'myapp_test'
},
migrations: {
directory: __dirname + '/migrations'
},
seeds: {
directory: __dirname + '/seeds'
}
}
};
3. 创建模型
接下来,定义你的数据模型。这些模型将继承自 objection.Model
。
const { Model } = require('objection');
class User extends Model {
static get tableName() {
return 'users';
}
// 可选:定义验证规则
static get jsonSchema() {
return {
type: 'object',
required: ['name'],
properties: {
id: { type: 'integer' },
name: { type: 'string', minLength: 1, maxLength: 255 },
email: { type: 'string', format: 'email' }
}
};
}
}
4. 执行数据库操作
现在你可以开始执行 CRUD 操作了。
创建记录
async function createUser(name, email) {
const user = await User.query().insert({ name, email });
console.log(user);
}
查询记录
async function getUserById(id) {
const user = await User.query().findById(id);
console.log(user);
}
更新记录
async function updateUser(id, updates) {
const user = await User.query().patchAndFetchById(id, updates);
console.log(user);
}
删除记录
async function deleteUser(id) {
const result = await User.query().deleteById(id);
console.log(result); // 返回影响的行数
}
5. 连接数据库并运行
最后,在你的应用入口文件中连接数据库并运行上述函数。
const { Model } = require('objection');
const Knex = require('knex');
const User = require('./models/User'); // 假设 User 模型在 models 目录下
const knex = Knex(require('./knexfile'));
Model.knex(knex);
(async () => {
await createUser('John Doe', 'john@example.com');
await getUserById(1);
await updateUser(1, { name: 'Jane Doe' });
await deleteUser(1);
})();
以上就是使用 Objection.js 的基本流程。你可以根据需要扩展模型功能,如关联查询等。
Objection.js 是一个强大的 Node.js ORM 框架,它基于 knex.js 构建,让你可以更优雅地操作数据库。首先,你需要安装 objection 和 knex:
npm install objection knex
接着,在你的项目中配置 knex,指定数据库连接信息。
创建一个模型类,继承自 objection.Model
:
const { Model } = require('objection');
class User extends Model {
static get tableName() {
return 'users';
}
}
module.exports = User;
现在你可以用这个模型来执行 CRUD 操作了:
- 查询:
User.query().where('name', 'John')
- 插入:
User.query().insert({ name: 'John' })
- 更新:
User.query().patch({ name: 'Johnny' }).where('id', 1)
- 删除:
User.query().delete().where('id', 1)
是不是很简单?Objection.js 还支持更复杂的查询和关系管理,让数据库操作变得既简单又有趣!
Objection.js 是一个基于 Knex.js 的 Node.js ORM 框架,它提供了强大的查询构建功能以及模型验证等特性。下面是如何开始使用 Objection.js 的步骤。
1. 安装
首先,确保已经安装了 Node.js 和 npm。然后,在你的项目中安装 objection 和 knex:
npm install objection knex
同时,你需要选择一个数据库适配器,例如 sqlite3
、mysql
或 pg
(PostgreSQL)。这里以 PostgreSQL 为例:
npm install pg
2. 配置 Knex
创建一个 knexfile.js
文件来配置你的数据库连接:
const path = require('path');
module.exports = {
client: 'pg',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'your_database_name'
},
migrations: {
directory: path.join(__dirname, 'src', 'db', 'migrations')
},
seeds: {
directory: path.join(__dirname, 'src', 'db', 'seeds')
}
};
3. 创建模型
接下来,定义你的数据模型。这里我们创建一个简单的 User
模型:
const { Model } = require('objection');
class User extends Model {
static get tableName() {
return 'users';
}
// 可选:定义 JSON schema 进行验证
static get jsonSchema() {
return {
type: 'object',
required: ['name'],
properties: {
id: { type: 'integer' },
name: { type: 'string', minLength: 1, maxLength: 255 },
email: { type: 'string', format: 'email' }
}
};
}
}
module.exports = User;
4. 使用模型
现在你可以使用这个模型进行 CRUD 操作了。以下是一些基本的例子:
const User = require('./models/User');
const knex = require('./knexfile'); // 确保这里的路径正确
// 创建用户
async function createUser(name, email) {
const newUser = await User.query().insert({ name, email });
console.log(newUser);
}
// 查询用户
async function findUserById(id) {
const user = await User.query().findById(id);
console.log(user);
}
// 更新用户信息
async function updateUser(id, updates) {
const updatedUser = await User.query().patchAndFetchById(id, updates);
console.log(updatedUser);
}
// 删除用户
async function deleteUser(id) {
const deletedCount = await User.query().deleteById(id);
console.log(deletedCount);
}
这些就是使用 Objection.js 基本流程和一些示例代码。通过这种方式,你可以更方便地管理数据库操作,并且利用 Objection.js 提供的强大功能如模型验证等。
Objection.js 是一个基于 Knex.js 的 Node.js ORM 框架。使用时首先安装 objection 和 knex:
npm install objection knex
然后配置 knex 连接数据库:
const knex = require('knex')({
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test'
}
});
定义模型继承自 objection.Model
:
const { Model } = require('objection');
class User extends Model {
static get tableName() {
return 'users';
}
}
之后就可以进行增删改查操作,例如获取所有用户:
User.query().then(users => {
console.log(users);
});
这就是使用 objection.js 的基本步骤。