What could be causing app.put() to fail in updating documents within mongodb?

I am currently working on implementing a form in an ejs file where, upon clicking a button, the "likes" attribute of a displayed document from my mongoDB collection should be set to 0 using a "PUT" request. However, for some reason, the document does not update as expected and I am unsure why.

No errors are being displayed in the console.

<!--The file is named "home.ejs"-->

<!--This section displays the document:-->
      <form action="/" method="GET">
            <h3> MONGO FETCHED: </h3>
            <ul>
                <li>
                    <span><%= numbers.usertext %></span>
                    <h3><%= numbers.likes%></h3>
                </li>
            </ul>
        </form>

<!--When the "upvote" button is clicked, it should trigger index.js 
to update the "likes" attribute of the displayed document and set it to 0. 
However, this functionality is not working as intended.-->
        <div>
            <form action="/" method="PUT">
                <button id="upvote" type="submit">upvote</button>
            </form>
        </div>

Within my index.js file, a random document from my collection is fetched to display to the user. I have also configured body-parser, ruling that out as the source of the issue.

MongoClient.connect(DBconnection, { useUnifiedTopology: true})
    .then(client => {
    console.log(`Connected to database: ${database}`);
    console.log(`Connected to table: ${table}`);

    app.use(bodyParser.urlencoded({ extended: true }));
    app.set('views', './views');
    app.set('view engine', 'ejs');

    const db = client.db(database);
    const collection = db.collection(table);    
            
    const w = db.collection(table).find().limit(-1).skip(R-1).next()
    //Where R is previously defined as a random number

//This retrieves the randomly fetched document, w, and then renders it on home.ejs
    app.get('/', (req, res) => {
        w
        .then(numbers => {
          res.render("home.ejs", { numbers: numbers});
        })
        .catch(error => console.error(error));
    })

//This route submits data into the database from a separate file not related to home.ejs
    app.post(`/${table}`, (req, res) => {
        collection.insertOne(req.body)
        .then(result => {
            res.redirect('/')
        })
        .catch(error => console.error(error))
    });

//The intention here is to update the "likes" attribute of the document w (defined earlier)
//and set it to 0. However, this code block is failing to perform as expected.
    app.put(`/${table}`, (req, res) => {
        db.collection(table).findOneAndUpdate({w}, {$set: {likes: "0"} })
        .then(result => {
            console.log("updated successfully");
        })
        .catch(error => console.error(error))
    });


});

Your insights and suggestions would be greatly appreciated. Thank you.

Answer №1

The code has a few issues that need to be addressed.

  1. It is not appropriate to use a form method of PUT in your EJS file. Valid methods for HTML forms are GET and POST.
  2. There is no route set up to handle the form submission.
  3. Express with EJS is designed as a server-side rendered application architecture. When you submit the form at the bottom, the page will be refreshed. If you want to avoid a full page refresh, you will need to incorporate some client-side JavaScript.

I recommend following an express form tutorial to gain a better understanding.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

Update Refresh Token within Interceptor prior to sending request

I'm stuck on this problem and could use some guidance. My goal is to refresh a user's access token when it is close to expiration. The authService.isUserLoggedIn() function returns a promise that checks if the user is logged in. If not, the user ...

When trying to run a jQuery function on click or load events, an error message stating that

When I have an .on(click) event triggering an ajax call, I want the same actions to occur when the page loads as well. My idea is to create a function that contains everything within the .on(click) event and trigger this function on page load. Although I ...

Browser Compatibility in Three.js

Could someone assist me with activating webgl on Internet Explorer version 8? I am able to use Firefox and Chrome without any issues. Your help would be greatly appreciated. ...

What is the best way to tally jsonObject instances within the same array based on their id or value

I have a jsonDataArray that contains two nested arrays with objects. My goal is to calculate the number of "duty" parentIds based on the teams' "value" as they have a one-to-one match. For instance, Team A with a value of 500 will have duties such as ...

Is there a common method for generating complex identifiers to be used as the HTML element's id, class, or name attributes

Is there a recommended method for "encoding" complex identifiers such as {Source:"ARCH.1", Code: "456-789.456 A+", SubNumber:##2} to be used in HTML elements' id, class, and name attributes? I could come up with something myself, but perhaps there is ...

"User-friendly Material-UI input field paired with a clear label

Seeking guidance on creating a text field with a label using the material-ui library. I am searching for something similar to this example: https://github.com/callemall/material-ui/blob/master/src/TextField/TextFieldLabel.jsx Unfortunately, I have been ...

What is the best way to eliminate additional values depending on the one I have chosen?

When utilizing the Vuetify v-autocomplete component with the multiple prop, we are able to select multiple values. How can I deselect other values based on the value I have selected? For instance: If I choose the main value, all others will be deselecte ...

Unexpected behavior observed in JavaScript and AJAX functionality

In my web development project, I've decided to incorporate JavaScript and AJAX for the signup form functionality. However, I seem to be facing some challenges as I try to post all the textbox values from the signup form through AJAX. The code snippe ...

Lack of animation on the button

Having trouble with this issue for 48 hours straight. Every time I attempt to click a button in the top bar, there is no animation. The intended behavior is for the width to increase and the left border color to change to green, but that's not what&ap ...

Overtaking a property in a node_module interface: a guide

I am facing a situation where I need to modify an existing interface property in my custom type declaration file, rather than creating a new one. Despite trying various approaches, such as attempting to omit the property, I have not been successful in ach ...

What is the best way to create divs that can close and hide themselves when clicked from inside the div itself?

I have a situation in my code where clicking a link reveals a div, and then the same link must be clicked again to hide it. However, I want to modify this so that any link within the div can also hide it when clicked. I currently have eight divs set up lik ...

Discover the ins and outs of the "DOM" within a string, treating it as HTML in AngularJS

Looking to extract data from a legal HTML string based on tags and attributes, but want to avoid using jQuery in favor of Angular. Are there built-in functions in Angular for this task? ...

What is the best way to assign an object variable within an array state?

My current state looks like this: const [tags, setTags] = useState([{id: 1, label: "random"}, {id: 2, label: "important"}]) const [input, setInput] = useState("") const [selectedTag, setSelectedTag] = useState([]) In addition ...

Alter the color of the text within the `<li>` element when it is clicked on

Here is a list of variables and functions: <ul id="list"> <li id="g_commondata" value="g_commondata.html"> <a onclick="setPictureFileName(document.getElementById('g_commondata').getAttribute('value'))">Variable : ...

Performing numerous file tasks concurrently? Utilize Node.js

I'm currently working on a node.js web application that allows users to submit content through a form, with the data being stored in a text file. I have a concern about what might happen if multiple people try to submit content simultaneously - could ...

Encountering difficulties with implementing and utilizing bootstrap in Symfony 5.3 with Encore plugin

While I am currently dealing with an older version of Symfony, I decided to create a new 5.3 Symfony application from scratch. However, I am facing difficulties when trying to integrate bootstrap into it. After consulting some documentation, I proceeded to ...

Parameters in functions are received by value

When working with JavaScript, one common point of confusion is the way variables are treated based on their data type. Variables of primitives are passed by value, while variables of objects are passed by reference. However, in function arguments, both pri ...

Steps to create an if statement using jQuery

.data( "autocomplete" )._renderItem = function( ul, item ) { return $( "<li></li>" ) .data( "item.autocomplete", item ) if ( ( item.parent_term_id == "16" ) ) { .append( "<a>" + (item.child_term ? item.child ...

What is the best way to style the current element being targeted in React?

In my React application, I am trying to dynamically adjust the height of a textarea element based on its content. I want to achieve this by utilizing an 'onchange' listener to trigger a resize function. While I have successfully implemented the ...