,

Node.js & Express.js Series | Chapter 18 – Removing Records from Database

Posted by

Node.js & Express.js Series | Chapter 18 | Deleting Records from database

Node.js & Express.js Series | Chapter 18 | Deleting Records from database

In this chapter, we will learn how to delete records from a database using Node.js and Express.js.

Step 1: Connect to the database

Before we can delete records from the database, we need to first establish a connection to the database. In this example, we will use MongoDB as our database.

    
      const mongoose = require('mongoose');
      mongoose.connect('mongodb://localhost:27017/myDatabase', {useNewUrlParser: true, useUnifiedTopology: true});
    
  

Step 2: Create a model

We need to create a model for the data we want to delete from the database. In this example, let’s assume we have a “User” model.

    
      const userSchema = new mongoose.Schema({
        name: String,
        email: String
      });

      const User = mongoose.model('User', userSchema);
    
  

Step 3: Delete records

Now that we have connected to the database and created a model, we can delete records from the database using the following code:

    
      User.deleteOne({ name: 'John' }, function (err) {
        if (err) return handleError(err);
        // deleted at most one user whose name is 'John'
      });
    
  

With the above code, we are deleting the first record in the database where the name is ‘John’. If you want to delete all records that match a certain condition, you can use `deleteMany` instead of `deleteOne`.

Conclusion

That’s it! In this chapter, we learned how to delete records from a database using Node.js and Express.js. We first connected to the database, created a model, and then used the model to delete records from the database. This is a fundamental operation when working with databases, and now you have the knowledge to perform it using Node.js and Express.js.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@user-jy8we8kl7k
6 months ago

I love this ❤❤
This is better than majority of Udemy courses