,

Chapter 14: How to Update Records in MongoDB Using PUT with Node.js & Express.js Series

Posted by

Node.js & Express.js Series | Chapter 14 | Updating records in MongoDB using PUT

Node.js & Express.js Series | Chapter 14 | Updating records in MongoDB using PUT

In this chapter, we will learn how to update records in MongoDB using the PUT method in Node.js and Express.js.

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js
  • Express.js
  • MongoDB

Updating Records in MongoDB using PUT

To update a record in MongoDB using the PUT method, we need to first establish a connection to the database using a Node.js driver such as Mongoose. Once the connection is established, we can define a route in our Express.js application to handle the update request.

Here is an example of how to update a record in MongoDB using the PUT method:

      
        const express = require('express');
        const mongoose = require('mongoose');
        
        const app = express();
        
        mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true });
        
        const schema = new mongoose.Schema({
          name: String,
          age: Number
        });
        
        const Model = mongoose.model('Model', schema);
        
        app.put('/update/:id', async (req, res) => {
          try {
            const updatedRecord = await Model.findByIdAndUpdate(req.params.id, req.body, { new: true });
            res.json(updatedRecord);
          } catch (error) {
            res.status(500).json({ message: error.message });
          }
        });
        
        app.listen(3000, () => {
          console.log('Server is running on port 3000');
        });
      
    

In this example, we define a route that listens for PUT requests to the ‘/update/:id’ endpoint. We use the Model.findByIdAndUpdate method provided by Mongoose to update the record with the specified id. The updated record is then returned as a JSON response.

Conclusion

In this chapter, we learned how to update records in MongoDB using the PUT method in Node.js and Express.js. We used Mongoose to establish a connection to the database and to perform the update operation. You can now use this knowledge to build applications that can update records in MongoDB using PUT requests.