How to undo soft deletion in Sequelize.js

I am using Sequelize.js in paranoid mode in my node.js project, and while soft deletion works as expected when searching and deleting data, I am having trouble finding a way to recover deleted deleted rows.

I know that I can get deleted rows using as described in docs

Model.findAll({paranoid: false, where: {deletedAt: {ne: null}}}) 

but paranoid: false is not available if update .

Is undeleting soft deleted lines even possible in Sequelize or am I just missing something?

+6
source share
3 answers

You can use instance.setDataValue('deletedAt', null) :

 var Bluebird = require('bluebird'); var models = require('./models'); models.sequelize.sync({ force: true }) .then(function () { return models.User.create({ name: 'user' }) }) .then(function (user) { return user.destroy() }) .then(function () { return models.sequelize.models.User.findAll({ paranoid: false }); }) .then(function (users) { var user = users[0]; user.setDataValue('deletedAt', null); return user.save({ paranoid: false }); }).then(function () { return models.sequelize.models.User.findAll(); }).then(function (users) { console.log(users[0]); }); 

Note that this snippet uses Sequelize @ v2

+10
source

Get your object using the {paranoid: false} option, i.e. var model = Model.findOne({ where: { something: 1 }, paranoid: false }) and then restore it to model.restore() http://docs.sequelizejs.com/en/latest/api/instance/# restoreoptions-promiseundefined

+7
source

I tried to use the instance update method instead of saving. This only works when adding the deletedAt set null value to the update data.

 user.setDataValue('deletedAt', null); user.update({deletedAt:null}, callback); 

In this case, the paranoid option is not required in the update.

0
source

Source: https://habr.com/ru/post/978086/


All Articles