跳到主要内容

模型修改

模型修改是 RxDB 的核心功能之一,它允许你创建、更新和删除数据库中的数据。RxDB 提供了简洁的 API 来操作数据,并自动处理数据验证、事件触发和变更记录。

创建数据

实例化后保存

const todo = new Todo({
title: '完成文档',
completed: false
});
await todo.save();

使用 Repository 创建

import { firstValueFrom } from 'rxjs';

// 创建实体实例
const todo = new Todo({
title: '完成文档',
completed: false
});

// 通过 repository 创建
const created = await Todo.create(todo);

更新数据

修改实例后保存

todo.title = '更新的标题';
todo.completed = true;
await todo.save();

使用 Repository 更新

// 部分更新
const updated = await Todo.update(todo, {
completed: true
});

重置未保存的更改

// 撤销未保存的修改
todo.reset();

删除数据

调用实例方法

await todo.remove();

使用 Repository 删除

await Todo.remove(todo);

批量操作

使用 EntityManager

import { inject } from '@angular/core';
import { RxDB } from '@aiao/rxdb';

const rxdb = inject(RxDB);

// 批量保存(创建或更新)
const todos = [new Todo({ title: '任务1', completed: false }), new Todo({ title: '任务2', completed: false })];
await rxdb.entityManager.saveMany(todos);

// 批量删除
const completedTodos = await firstValueFrom(
Todo.findAll({
where: {
combinator: 'and',
rules: [{ field: 'completed', operator: '=', value: true }]
}
})
);
await rxdb.entityManager.removeMany(completedTodos);

实体状态管理

检查实体状态

import { getEntityStatus } from '@aiao/rxdb';

const status = getEntityStatus(todo);
console.log(status.local); // 是否已保存到本地
console.log(status.modified); // 是否有未保存的修改
console.log(status.fingerprint); // 实体指纹

重置实体

// 撤销所有未保存的修改
todo.reset();

事务支持

RxDB 支持事务操作,确保数据一致性:

// 注意:具体事务 API 需要根据适配器实现
// 以下为概念示例

await rxdb.transaction(async () => {
const todo = new Todo({
title: '事务中的任务'
});
await todo.save();

// 如果事务中任何操作失败,所有更改都会回滚
const anotherTodo = await firstValueFrom(
Todo.findOne({
where: {
combinator: 'and',
rules: [{ field: 'title', operator: '=', value: '已存在的任务' }]
}
})
);
if (anotherTodo) {
anotherTodo.completed = true;
await anotherTodo.save();
}
});