首页 > 解决方案 > 在数据库 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 种子在表项中插入所有预注册项,我的数据库是:迁移后的数据库

将请求发送到服务器后,返回创建但未插入数据库的对象,如图所示:发送请求后的数据库

标签: typescriptsqliteexpressknex.js

解决方案


仅在完成交易时使用

await trx.commit()

推荐阅读