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. |
-
Drag and drop the nodes onto the dashboard in
the specified order:

-
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.

-
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.

-
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.

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.
Note: To learn more about MongoDB operators, refer to the MongoDB documentation.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:

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

-
http response
Leave the node without any changes.
- 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.
