To update a document in a MongoDB collection using Mongoose.
we can use the "updateOne()" or "updateMany()" method provided by Mongoose models.
First, define a Mongoose model that corresponds to the collection you want to update.
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;
We can now use the "updateOne()" or "updateMany()" method provided by the "EmployeeModel" model to update documents in the "Employee" collection.
These methods take two arguments:
Filter documents to update.
Update filtered documents in the Collection.
We can use the "updateOne()" method to update a specific document that matches the filter criteria.
const EmployeeModel = require("./employeeModel"); async function updateEmployeeDetail(req, res) { // Update Employee with a specific name and updated department and age // For Demo Purpose we are updating directly. // Retrieve updates values from req.body return await EmployeeModel.updateOne( { email: 'Alice.collin@example.com' }, { age: 20, department: "Finance" } ) .then((emp) => { console.log('Updated Employee returned:', emp); res.end(JSON.stringify(emp)); }) .catch((err) => { console.error('Error while updating employee:', err); res.end(JSON.stringify(err)); }); } module.exports = { updateEmployeeDetail };
We can also use the "updateMany()" method to update multiple documents that match the filter criteria.
const EmployeeModel = require("./employeeModel"); async function updateEmployeesDetail(req, res) { // Update All Employees which match the criteria in Employee Collection // For Demo Purpose we are updating directly. // Retrieve updates values from req.body return await EmployeeModel.updateMany( { department: "Finance", age: { $lt: 23 } }, { department: "HR" } ) .then((employees) => { console.log('All Employees Documents updated successfully:', employees); res.end(JSON.stringify(employees)); }) .catch((err) => { console.error('Error while updating Employees:', err); res.end(JSON.stringify(err)); }); } module.exports = { updateEmployeesDetail };
Above Statement, will asynchronously update all documents in the "Employee" collection where the "age" is less than "23" and the "department is "Finance", and set the department to "HR".
import the `updateEmployeeDetail` and `updateEmployeesDetail` functions from the `employeeController` file and place them inside `/update-employee` and `update-employees` conditions respectively.
let http = require("http"); const url = require("url"); const dbConnection = require("./db"); const { updateEmployeeDetail, updateEmployeesDetail } = 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 === "/update-employee") { updateEmployeeDetail(req, res); } else if (pathname === "/update-employees") { updateEmployeesDetail(req, res); } else { res.end("Server Listening..."); } }) .listen(3002, () => { console.log(`server listening on port 3002!`); dbConnection(); });
To update employee data within Collection, we often use the `PUT` HTTP Method to update data in DBs, but for testing if you try to hit GET Request on `http://localhost:3002/update-employee` and `http://localhost:3002/update-employees` from a web browser. it will return the updated document count from the Collection if it exists.