nodejs delete in mysql

Deleting Data from MySQL using Node.js

If you are working with MySQL database using Node.js, it is important to know how to delete data from the database. Deleting data is one of the important operations in database management.

Using DELETE Query

The most common way to delete data from a MySQL database using Node.js is by using the DELETE query. The DELETE query removes one or more rows from a table based on a specific condition.


const mysql = require('mysql');

// Create a connection
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

// Delete data from the table
connection.query("DELETE FROM table_name WHERE condition", function (error, result) {
  if (error) throw error;
  console.log(result.affectedRows + " record(s) deleted");
});

The code above demonstrates how to use the DELETE query in Node.js. You need to replace the username, password, database_name, table_name, and condition with their respective values.

Using ORM Libraries

Another way to delete data from a MySQL database using Node.js is by using ORM (Object-Relational Mapping) libraries such as Sequelize, TypeORM, and Bookshelf. ORM libraries provide a higher level of abstraction and make it easier to work with databases.

Here is an example using Sequelize:


const Sequelize = require('sequelize');

// Create a connection
const sequelize = new Sequelize('database_name', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});

// Define a Model
const User = sequelize.define('user', {
  // attributes
  firstName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  lastName: {
    type: Sequelize.STRING
    // allowNull defaults to true
  }
}, {
  // options
});

// Delete data from the table
User.destroy({
  where: {
    id: 1
  }
}).then(() => {
  console.log("Data deleted successfully");
}).catch((error) => {
  console.log("Error deleting data", error);
});

The code above demonstrates how to delete data from a MySQL database using Sequelize ORM library. You need to replace the username, password, and database_name with their respective values. You also need to define the model for the table.

Conclusion

Deleting data from a MySQL database using Node.js is an important aspect of database management. The DELETE query is the most common way to delete data. ORM libraries such as Sequelize, TypeORM, and Bookshelf provide a higher level of abstraction and make it easier to work with databases.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe