Sequelize:销毁/删除表中的所有记录

use*_*173 23 mysql node.js sequelize.js

我正在使用Mocha进行单元测试.

测试开始时,我想删除表中的所有先前记录.

我尝试过的:

db.User.destroy({ force: true }).then(() => {
}).then(() => done());


db.User.destroy(
    {where: undefined},
    {truncate: false}
).then(() => {
    return 
}).then(() => done());


db.User.destroy({}).then(() => {
    return db.User.bulkCreate(users)
}).then(() => done());
Run Code Online (Sandbox Code Playgroud)

我一直收到以下错误:

 Error: Missing where or truncate attribute in the options parameter of model.destroy.
Run Code Online (Sandbox Code Playgroud)

如何删除/销毁表中的所有记录?

mah*_*hiv 41

你可以尝试使用

db.User.destroy({
  where: {},
  truncate: true
})
Run Code Online (Sandbox Code Playgroud)

  • 你不需要 where 选项。`db.User.destroy({ truncate: true })` 没问题 (3认同)
  • 如果您有外键约束,“truncate: true”可能不起作用。在这种情况下,您只需删除该子句即可。 (3认同)
  • 我只做了 `users.destroy({ where: {} })` 并且它有效 (3认同)
  • @Coxer,事实并非如此。您将收到“UnhandledPromiseRejectionWarning:错误:在 model.destroy 的 options 参数中缺少 where 或 truncate attribute”错误 (2认同)

小智 10

我能够用代码解决这个问题:

table.sync({ force: true });
Run Code Online (Sandbox Code Playgroud)

这是比maheshiv 的回答中提出的解决方案更安全的解决方案。