MongoDB is the most used cross-platform, document-oriented database that provides, high availability, high performance, and easy scalability. MongoDB works on the concept of collecting and documenting the data. findByIdAndRemove() stands proud as a convenient way to discover a file by its specific identifier and eliminate it from the database.
Prerequisites
The findByIdAndRemove()
function is part of the Mongoose library and is used to find a matching document, remove it, and pass the found document (if any) to the callback.
Creating Express Application and setting up MongoDB
Step 1: Initialise an Express application with the following command.
npm init -y
Step 2: Install the required dependencies.
npm install express mongoose
Folder Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"mongoose": "^8.0.3"
}
Data collection before the operation.
Example: Add the following code in index.js file.
//app.js const mongoose = require( 'mongoose' );
// Database connection useNewUrlParser: true ,
useCreateIndex: true ,
useUnifiedTopology: true ,
useFindAndModify: false
}); // User model const User = mongoose.model( 'User' , {
name: { type: String },
age: { type: Number }
}); // Find a document whose // user_id=5eb987e377d884411cac6b69 and remove it var user_id = '5eb987e377d884411cac6b69' ;
User.findByIdAndRemove(user_id, function (err, docs) {
if (err) {
console.log(err)
}
else {
console.log( "Removed User:" , docs);
}
}); |
Steps to run the program:
node index.js
Output