Update data with PUT

Let's learn how to update data in your database using the PUT method.

To start working on CRUD operations, make sure your Node-RED environment is connected to your MongoDB database.

To build the PUT method, we will need the following nodes:

Node Description
http in Listens to HTTP requests.
function Allows to write custom JavaScript code to manipulate data passed through it.
mongodb out Allows data to be stored, updated, or removed from a MongoDB collection.
http response Replies to HTTP requests.
Note: To learn more about Node-RED nodes, refer to the chapter ../useful%20info/common_node_red_nodes.html.
  1. Drag and drop the nodes onto the dashboard in the specified order:
    Screenshot
  2. To connect a node to the next one, click on the gray square on its right border and drag your mouse to the gray square on the left border of the next node. You will see a line linking the two nodes. Now, we are ready to configure each of the nodes.
    Screenshot
  3. http in

    Double-click on the node to open its properties. Set the method to PUT, name the endpoint for your URL, and then click Done.


    Screenshot
  4. function

    To update an object, let's identify it by the object ID that MongoDB generates automatically for its records. To do this, open the Setup tab in the function's properties, add a module, and set it to objectid.


    Screenshot

    Return to the On Message tab and enter a descriptive name for your function.

    Now, let's update the function's body to meet our needs.

    First, we will specify the id of the entry to be updated in the msg.query object using the _id property received in the body of the HTTP request. Then, we will delete the _id from the msg.payload object since MongoDB doesn't allow id modification. Finally, we'll use the MongoDB $set operator to specify the fields to update and their new values.

    Copy the following code at the beginning of the function's body:

    msg.query = {
      _id: objectid(msg.payload._id),
    };
    
    delete msg.payload._id;
    
    msg.payload = {
      $set: msg.payload,
    };

    Your function should now appear like this:


    Screenshot
  5. mongodb out

    Specify the collection name in MongoDB, set the operation to update, and then click Done.


    Screenshot
  6. http response

    Leave the node without any changes.

  7. Deploy the service.

The API is now ready to update existing entries in the database using the PUT method.

To test your REST API, you can use a platform like Postman.