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.