Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include the deleted elements when querying a "paranoid" table on sequelize.js?

I want that previously existing users on my application, that have been deleted using the paranoid mode (so now its field deletedAt is NOT null), to be able to register again using the same email. So when the API notices a user creation with a previously used email it sets to null the deletedAt field of the previously existing register instead of creating a new user.

Usually for looking for an user I will do,

User.find( { where: { email: req.body.user.email } })

But upon inspection of the SQL query created, it includes

Users.deletedAt IS NULL

Is there any special way of finding when dealing with paranoid models?

like image 285
alilloig Avatar asked Jul 07 '14 13:07

alilloig


3 Answers

Just run your query like this:

User.find({   where: {email: req.body.user.email},    paranoid: false }) 
like image 151
lao Avatar answered Oct 12 '22 03:10

lao


Sequelize has this feature built in. Per their API docs, you can include the 'paranoid' flag in the options of your find call.

e.g.

User.find({where: {email: req.body.user.email}}, {paranoid: false}).success(models) {     //models contains both deleted and non-deleted users } 

Reference: http://docs.sequelizejs.com/en/latest/api/model/#findalloptions-promisearrayinstance

like image 37
rudd Avatar answered Oct 12 '22 03:10

rudd


You can use hook.

var uuid = require('node-uuid')
module.exports = function (sequelize, DataTypes) {
    return sequelize.define("multi_route", {
        email: {
            type: DataTypes.STRING,
            unique: false,
        }
        //other fields
    }, {
        timestamps: true,
        paranoid: true,
        hooks: {
            beforeUpdate: function (multiFare, next) {                  // berforeUpdate will called after beforeDestroy
                if (multiFare.email.indexOf("_____destroyed") > -1) {   // check contains '_____destroyed' string
                    multiFare.email = multiFare.email + uuid.v1()       // set unique value
                }
                next()
            },
            beforeDestroy: [function (multiFare, next) {                // beforeDestroy will called before one instance destroyed
                multiFare.email = multiFare.email + '_____destroyed'    // flag this will destroy
                next()
            }]
        }
    })
}

Sorry for my bad comments :(

like image 33
Enxtur Avatar answered Oct 12 '22 02:10

Enxtur