Home > Net >  UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function (NodeJS- Sequelize)
UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function (NodeJS- Sequelize)

Time:09-07

I'm following a tutorial on NodeJs on youtube, but when it comes to deleting users by id, it doesn't work like what's on the tutorial. But on that video everything seems to work perfectly. This is my code. Where am I wrong? Looking forward to everyone's comments.

let deleteUserByID = (userId)=>{
    return new Promise(async(resolve, reject)=>{
        try{
            let user = await db.User.findOne({
                where: {id: userId}
            })
            if(user){
                await user.destroy();
   
            }
            resolve();
        }catch(e){
            reject(e);
        }
    })
}

And this is the error displayed on the terminal screen:

(node:11140) UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function
at...
at...
at...
...
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11140) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch 
block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:11140) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

CodePudding user response:

After a while of searching on the internet, i found the solution, everything is working and seems to be fine, anyone can refer to it if they have the same error as mine. Upvote if it works for you

let deleteUserByID=(userId)=> {
    return db.User.destroy({ where: { id: userId } })
     .then(rows => Promise.resolve(rows === 1))
   }

CodePudding user response:

Or another solution:

let deleteUserByID=(userId)=> {
       return new Promise(async ( resolve, reject)=>{
         await db.User.findOne({
            where:{id: userId}
        })
       
        await db.User.destroy({
            where:{id: userId}
        })
        resolve({
            errCode:0,
            message: `The user is deleted`
        })
    })
   }

  • Related