How to Delete Data from MongoDB with Node.js and Mongoose

2020/8/113 min read
bookmark this
Responsive image

This blog will show a tutorial about how to delete data from MongoDB by using Node.js with Mongoose. Mongoose is the Object Data Modeling library for MongoDB and Node.js. It provides functions for schema, query building, and more. If you don't use Mongoose to access MongoDB with Node.js, then you can use the MongoDB package for Node.js directly. 

Get Start

First, initialize a new npm package, we'll create a new package and new file, and add our code for how to insert data to MongoDB.

npm init -y

Next, let's install the mongoose package, this will be the only package we'll use for this tutorial. 

npm install --save mongoose

Create an index.js, we'll add our code to this file to connect to MongoDB and insert data to the Database.

Connect to the MongoDB

Now, the following is a sample code to connect to MongoDB. Assume you already set up MongoDB at your local and has a database as your-database.

const {connect} = require('mongoose');

connect('mongodb://localhost:27017/your-database')
.then(() => {
    console.info('connect successfully')
})
.catch(() => {
    console.error('connection error');
});

Defined MongoDB Schema

Here, we'll define our collection in MongoDB, the collection name will be my-collection-name.

let localModel = new Schema({
    key: {
        type: String
    },
    value: {
        type: String
    },
    culture: {
        type: String
    }
})

let localSchema = model('localization', localModel, 'my-collection-name');

Insert some data to MongoDB

Before we can try the Mongoose Delete function, let's add some test data. The following code will add 100 different records into the collection.

const createTestMillionAsync = async(roopLimit) => {
    let timerName = `insert-timer-${roopLimit}`;
    console.time(timerName)
    let testTargetList = [];
    for (let index = 0; index < roopLimit; index++) {
    
        testTargetList.push({
            key: `test-key-${index}`,
            value: `my test value : ${index}`,
            culture: 'en-US'
        });    
    
    }
    
    await localSchema.insertMany(testTargetList);

    console.timeEnd(timerName);
}

createTestMillionAsync(100);

Try delete Records with Mongoose

The following is example is for deleting the specific record, so you just need to call the deleted one and pass the _id value.

const removeDataAsync = async() => {
    
  let result = await localSchema.deleteOne({
        _id: '60a872a9d3ed022504e3aa01'
    });
    if (result) {
        console.info('update successfully', result);
    }
}

removeDataAsync();

In case you want to delete everything from the collection, you can try the following code. 

const removeDataAsync = async() => {
    
    let result = await localSchema.deleteMany({});
    if (result) {
        console.info('update successfully', result);
    }
}

removeDataAsync();

Conclusion

Above is how you can use the delete function with Mongoose to MongoDB by using Node.js.