Sequelize(使用 NextJS)sync() 两次

问题描述 投票:0回答:1

我正在将 Sequelize 与 nextjs 一起使用。在 DELETE 操作期间,它执行两次sync()。这是问题还是正常现象?

我在下面分享我的代码。

// sequelize.ts
import { Sequelize } from 'sequelize-typescript';
import { Person } from './models/person';
import * as _mariadb from 'mariadb';

export const sequelize = new Sequelize({
  dialect: 'mariadb',
  dialectModule: _mariadb,
  database: 'nextjs',
  username: 'root',
  password: 'xyz',
  models: [Person]
});

sequelize.sync()
  .then(() => {
    console.log('Database & tables created!');
  })
  .catch(error => console.error('Sequelize initialization error:', error));
//routes.ts
import { Person } from "@/app/database/models/person";
import { sequelize } from "@/app/database/sequelize";


export async function GET(_request: Request, {params}: {params: {id: string}})
{
    await sequelize.authenticate(); // without that getting error: ModelNotInitializedError: Model not initialized: Member "findOne" cannot be called. "Person" needs to be added to a Sequelize instance.
    const testData = await Person.findOne({where: {id: parseInt(params.id)}});
    return Response.json(veri);
}

export async function DELETE(request: Request, {params}: {params: {id: string}})
{
    const index = await Person.findOne({where: {id: parseInt(params.id)}});
    const testData = index?.username;
    index?.destroy();
    return Response.json(testData);
}

这里记录:

Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'Person' AND TABLE_SCHEMA = 'nextjs'
Executing (default): SELECT 1+1 AS result
Executing (default): SHOW INDEX FROM `Person` FROM `nextjs`
Executing (default): SELECT `id`, `username`, `password`, `createdAt`, `updatedAt` FROM `Person` AS `Person` WHERE `Person`.`id` = 5;
Database & tables created!
Executing (default): DELETE FROM `Person` WHERE `id` = 5
 DELETE /comments/5 200 in 284ms
Executing (default): SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME = 'Person' AND TABLE_SCHEMA = 'nextjs'
Executing (default): SHOW INDEX FROM `Person` FROM `nextjs`
Database & tables created!

问题:创建了数据库和表!似乎出现了两次。

我尝试更改 orm 查询;

await Person.findOne({where: {id: parseInt(params.id)}}).then(x => x?.destroy());
但问题不在于它。

然后我尝试了

return new Response("x");
而不是
return Response.json();
,但不是关于它。

database next.js request synchronization sequelize.js
1个回答
0
投票

调用sync()两次是不必要的,特别是在处理大型数据库时,为了防止这种情况,只能在应用程序/服务器启动时调用它,并从请求或路由处理程序中删除不必要的调用,并确保删除任何会触发的条件逻辑再来一次。

© www.soinside.com 2019 - 2024. All rights reserved.