Open In App

Mongoose QueriesModel.findByIdAndDelete() Method

Last Updated : 17 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Queries findByIdAndUpdate() method is used to search for a matching document, and delete it. It then returns the found document (if any) to the callback. This function uses this function with the id field.

Installation of Mongoose Module:

Step 1. You can visit the link to Install the mongoose module. You can install this package by using this command.

npm install mongoose

Step 2. You may use the command to check your mongoose version at the command prompt after installing the module.

npm version mongoose

Step 3. Following that, you can simply make a folder and include a file, like index.js. You must perform the following command in order to run this file.

node script.js

Syntax:

Model.findByIdAndDelete(id, options, callback)

Parameters: This method accepts four parameters as mentioned above and described below.

  • id: It is the Id to which is searched. This can be in an Object, Number, or String.
  • options: These options can be: 
    • strict: This can be a boolean or string type option. It overrides the strict mode setting in the schema.
  • callback: This is a callback function that will be executed once our query gets executed successfully.  This is an optional parameter.

Project Structure: 

 

Our project is now ready, but we must first establish the database before we can work on it. We are building a database with MongoDB Cloud. The “people” collection, which we are using to create the “test” database, contains two documents. This is how the database will seem when it has been created:

initial output

Example 1: In this example, We are discussing the use of the findByIdAndDelete function and delete document with the name ‘Dadu’.

Filename: script.js

Javascript




// Require the mongoose module
const mongoose = require('mongoose');
 
// Path to our cloud DataBase
 
// Connecting to database
mongoose.set('strictQuery', false);
 
mongoose.connect(url)
    .then((ans) => {
        console.log("Connected Successful")
    })
    .catch((err) => {
        console.log("Error in the Connection")
    })
 
// Calling Schema class
const Schema = mongoose.Schema;
 
// Creating Structure of the model
const schema = new Schema({
    firstName: {
        type: String,
        require: true,
    },
    lastName: {
        type: String,
        require: true,
    }
});
// Compile our model
const Person = mongoose.model('Person', schema);
 
// Person.create({firstName: 'Gushan', lastName: 'Sahu'})
const deleteDocument = (id) => {
    try {
        Person.findByIdAndDelete(id,
            (err, x) => {
                if (err) console.log(err)
                else {
                    console.log('Deleted Successful!!')
                }
            })
 
    } catch (error) {
        console.log(error);
    }
}
 
let id = '63b5682c4853d8e67cc1dac3';
 
deleteDocument(id);


After establishing the connection to our “test” database, we constructed and modeled the schema for our “people” collection in the test database. Then, we built the function deleteDocument, which requires the employee’s id to carry out an delete operation.

The id parameter is passed to the findByIdAndDelete() function inside the deleteDocument function to carry out the delete operation. These are contained within a try/catch block so that an error will be caught if the operation fails. 

Run the index.js file using the below command:

node script.js

output2

After the function is executed, We can see in the database that the particular employee data is deleted as shown below:

output3

Example 2: In this example, we are going to delete multiple documents from the database. 

Filename: script2.js

Javascript




// Require the mongoose module
const mongoose = require('mongoose');
 
// Path to our cloud DataBase
 
// Connecting to database
mongoose.set('strictQuery', false);
 
mongoose.connect(url)
    .then((ans) => {
        console.log("Connected Successful")
    })
    .catch((err) => {
        console.log("Error in the Connection")
    })
 
// Calling Schema class
const Schema = mongoose.Schema;
 
// Creating Structure of the model
const schema = new Schema({
    firstName: {
        type: String,
        require: true,
    },
    lastName: {
        type: String,
        require: true,
    }
});
 
// Compile our model
const Person = mongoose.model('Person', schema);
 
const deleteDocument = (id) => {
    try {
        for (let i of id) {
            Person.findByIdAndDelete(id,
                { strict: false }
                , (err, x) => {
                    if (err) console.log(err)
                    else {
                        console.log('Successfully Deleted!!')
                    }
                })
        }
    } catch (error) {
        console.log(error);
    }
}
 
let id = [
    '63b57197e57166d139d5d8d1',
    '63b57197e57166d139d5d8d2',
    '63b57197e57166d139d5d8d3'
]
deleteDocumen(id);


This is how the database will be when it has been created:

output4

After the function is executed, We can see in the database that the particular employee data is deleted as shown below:

output5

Reference: https://mongoosejs.com/docs/api.html#model_Model-findByIdAndDelete



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads