How to Delete Rows of Data Using Sequelize

Sequelize.js delete query?

For anyone using Sequelize version 3 and above, use:

Model.destroy({
where: {
// criteria
}
})

Sequelize Documentation - Sequelize Tutorial

Sequelize: Destroy/Delete all records in the table

You can try using

db.User.destroy({
where: {},
truncate: true
})

sequelize - delete multiple rows and then bulk insert

For deleting the record using Sequelize, what you have used is right. It deletes the record based on the condition that you were providing like below. Sequelize documentation

Model.destroy({
where: {
// criteria
}
})

So you are using for loop to iterate over the list and delete it. But your custom function (deleteRows) is not supporting .then, so you are running in to problem of deleting the record.

I suggest you to make your function like below, using promise. it will return either resolve or reject. Promise Documentation

deleteRows: function(rows){
return new Promise(function(resolve, reject){
rows.forEach((row) => {
models.TABLE.destroy({ where: {CNTRY_CD: row['CNTRY_CD'], AREA_ID: row['AREA_ID'], BUS_DT: row['BUS_DT']}})
.then((region, err) => {
if(err) {
console.log("I am here");
reject('Internal Server Error');
}

resolve(region);
});
});
});
}

By using the promise you can able to use .then for you function. Which is as follows

deleteRows(req.body.rows).then(function(result){
// your logic
})

Similar you can use promise for adding the records too.

Second approach: You can use async await also for performing the same operation async await documentation

deleteRows: async function(rows) {

var result = await rows.forEach((row) => {
models.TABLE.destroy({
where: {
CNTRY_CD: row['CNTRY_CD'],
AREA_ID: row['AREA_ID'],
BUS_DT: row['BUS_DT']
}
})
.then((region, err) => {
return region
});
});

}

Sequelize - Delete all data before some hours from now

For that you need to use moment.

const expiryDate = 24;
const { Op } = require('sequelize');

await MyTable.destroy({
where: {
createdAt: {[Op.lte]: moment().subtract(expiryDate, 'hours').toDate()}
}
});


Related Topics



Leave a reply



Submit