To delete a document in a MongoDB collection using Mongoose.
we can use the "deleteOne()" or "deleteMany()" method provided by Mongoose models.
First, define a Mongoose model that corresponds to the collection you want to delete documents from.
const mongoose = require('mongoose'); const employeeSchema = new mongoose.Schema({ name: String, email: String, department: String, age: Number }); // Define a model based on the schema const Employee = mongoose.model('Employee', employeeSchema); module.exports = Employee;
Now, We can use the "deleteOne()" or "deleteMany()" method provided by the "EmployeeModel" model to delete documents from the "Employee" collection.
These methods take a filter object to specify the documents to delete.
We can use the "deleteOne()" method to delete specific a document that matches the filter criteria.
const EmployeeModel = require("./employeeModel"); async function deleteEmployee(req, res) { // Delete Employee with a specific name and age. // For Demo Purpose we are updating directly with GET HTTP Method. // we use DELETE HTTP Method to delete document. return await EmployeeModel.deleteOne({ name: 'Alice Collin', age: 20 }) .then((emp) => { console.log('Deleted Employee Successfully:', emp); res.end(JSON.stringify(emp)); }) .catch((err) => { console.error('Error while Deleting employee:', err); res.end(JSON.stringify(err)); }); } module.exports = { deleteEmployee };
We can also use the "deleteMany()" method to delete multiple documents that match the filter criteria.
const EmployeeModel = require("./employeeModel"); async function deleteEmployees(req, res) { // Delete All Employees which match the criteria in Employee Collection return await EmployeeModel.deleteMany({ department: "Finance"}) .then((employees) => { console.log('All Employees Documents deleted successfully:', employees); res.end(JSON.stringify(employees)); }) .catch((err) => { console.error('Error while deleting Employees:', err); res.end(JSON.stringify(err)); }); module.exports = { deleteEmployees };
import the `deleteEmployee` and `deleteEmployees` functions from the `employeeController` file and place them inside `/delete-employee` and `delete-employees` conditions respectively.
let http = require("http"); const url = require("url"); const dbConnection = require("./db"); const { deleteEmployee, deleteEmployees } = require("./employeeController"); http .createServer((req, res) => { res.writeHead(200, { "Content-Type": "text/html" }); // Parse the requested URL const parsedUrl = url.parse(req.url, true); const { pathname } = parsedUrl; if (pathname === "/delete-employee") { deleteEmployee(req, res); } else if (pathname === "/delete-employees") { deleteEmployees(req, res); } else { res.end("Server Listening..."); } }) .listen(3002, () => { console.log(`server listening on port 3002!`); dbConnection(); });
To delete employee data from Collection, we often use the `DELETE` HTTP Method to delete data from Collections, but for testing, if you try to hit GET Request on `http://localhost:3002/delete-employee` and `http://localhost:3002/delete-employees` from a web browser. it will return the deleted document count from the Collection if it exists.