实现SequelizeJS软删除的问题

时间:2018-11-17 23:05:35

标签: node.js postgresql express sequelize.js sequelize-cli

我正在尝试在SequelizeJS中实现“软删除”。因此,我在模型中添加了“ paranoid:true”,并在迁移中添加了“ deletedAt”列。我尝试使用另一个问题中的answer,但是由于版本不同,它无法正常工作。另外,我不确定是否正确编写了控制器。网上没有太多信息,所以我不确定如何检查我是否做对了。我正在使用Sequelize 5.3.0。 这是我的模型:

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Properties = sequelize.define('Properties', {
    name: {
      allowNull: false,
      type: DataTypes.STRING
    }
  }, {
    timestamps: true,
    paranoid: true
  });
  Properties.associate = function(models) {
    // associations can be defined here
    Properties.hasMany(models.Deals, {
      foreignKey: 'id',
      onDelete: 'CASCADE'
    })
  };
  return Properties;
};

这是我的移民:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Properties', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.INTEGER,
        autoIncrement: true
      },
      name: {
        allowNull: false,
        type: Sequelize.STRING
      }
      deletedAt: {
        type: Sequelize.DATE
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Properties');
  }
};

我已经从官方文档中找到了this解决方案,但对我来说没有意义:

User.findAll({
    include: [{
        model: Tool,
        where: { name: { [Op.like]: '%ooth%' } },
        paranoid: false // query and loads the soft deleted records
    }]
});

我的getAllProperties控制器:

getAllProperties: (req, res, next) => {
    return Properties
    .all()
    .then(properties => res.status(200).json({ status: 'Retrieved all properties', properties }))
    .catch(error => console.log(error));
  }

我的destroyProperty控制器:

destroyProperty: (req, res, next) => {
  const { id } = req.params;
  return Properties
  .findById(id)
  .then(property => {
    if (!property) {
      return res.status(404).send({ message: 'Property not found' })
    }
    return property
    .destroy()
    .then(() => res.status(200).json({ status: 'Deleted one property', property }))
    .catch(error => console.log(error));
  })
}

1 个答案:

答案 0 :(得分:0)

我发现我的模型和迁移是好的,事实是我在做sequelize db:migrate:undo:allsequelize db:migrate,但是数据库架构保持不变。因此,我做了sequelize db:dropsequelize db:create,然后它开始创建此字段。 另外,我更改了getAllProperties控制器:

getAllProperties: (req, res, next) => {
  return Properties
  .findAll({paranoid: false})
  .then(properties => res.status(200).json({ status: 'Retrieved all properties', properties }))
  .catch(error => console.log(error));
}

所有更改之后,它开始工作。

相关问题