typescript - 在数据库 knex 插入后,不将数据发送到数据库,而是返回数据
问题描述
我的 sqlite3、knex、typescript 和 express 路由有一个问题。
将请求发送到数据库后,我的函数会返回我的数据,但不会显示在我的 database.sqlite 中。
创建数据的函数:
async create(req: Request, res: Response) {
const {
name,
email,
whatsapp,
latitude,
longitude,
city,
uf,
items
} = req.body;
const trx = await knex.transaction();
const point = {
name,
email,
whatsapp,
latitude,
longitude,
city,
uf,
image: 'test'
}
const points = await trx('points').insert(point);
const point_id = points[0];
const receivedPointItems = items.map((item_id: number) => {
return {
item_id,
point_id
}
})
await trx('point_items').insert(receivedPointItems);
return res.send({receivedPointItems, point});
}
连接.ts
const connection = knex({
client: 'sqlite3',
connection: {
filename: path.resolve(__dirname, 'database.sqlite'),
},
useNullAsDefault: true,
});
迁移点
export async function up(knex: Knex) {
return knex.schema.createTable('points', (point) => {
point.increments('id').primary();
point.string('name').notNullable();
point.string('image').notNullable();
point.string('email').notNullable();
point.string('city').notNullable();
point.string('whatsapp').notNullable();
point.string('uf', 2).notNullable();
point.decimal('longitude').notNullable();
point.decimal('latitude').notNullable()
})
}
export async function down(knex: Knex) {
return knex.schema.dropTable('points');
}
物品迁移:
export async function up(knex: Knex) {
return knex.schema.createTable('items', (point) => {
point.increments('id').primary();
point.string('title').notNullable();
point.string('image').notNullable();
})
}
export async function down(knex: Knex) {
return knex.schema.dropTable('items');
}
point_items 迁移:
export async function up(knex: Knex) {
return knex.schema.createTable('point_items', (point) => {
point.increments('id').primary();
point.string('point_id').notNullable().references('id').inTable('points');
point.string('item_id').notNullable().references('id').inTable('items');
})
}
export async function down(knex: Knex) {
return knex.schema.dropTable('point_items');
}
运行我的代码迁移并创建数据库的所有表,并创建我的文件“database.sqlite”,并运行 knex 种子在表项中插入所有预注册项,我的数据库是:
解决方案
仅在完成交易时使用
await trx.commit()
推荐阅读
- android - 如何清除CachedNetworkImage颤动中的缓存
- mongodb - 无法连接到 Compass 中的副本集
- flutter - 如何知道 DraggableScrollableSheet 是折叠还是展开
- ios - 使用 Ionic 4 在 iOS 中直接调用而无需额外对话框
- r - 如何找到多分类 svm 的准确性?
- python - 为什么用 lambda 包装函数修复堆栈溢出?
- excel - 如何实现查询比较不同工作表中的 ID 并在相应行打印确认?
- excel - 在给定罢工、到期和日期的情况下提取历史期权收盘数据
- ansible - 如何增加主机上的值(Ansible)
- c++ - 如何为指令重新排序编写可观察的示例?