I'm currently working on The Odin Project's Library Project, but I'm utilizing MongoDB for my storage.
Currently, there is a field in my database that is called "read" and it's either true or false (as a string, not boolean).
What I want to do is with my addEventListener is to change the value from either true to false or false to true and write that with a put request. It'll then change my ejs file's class and change the color of the book based on true or false.
I've tried different const values, different read values in body, etc. I am assuming something is wrong with my app.put function?
JS:
const readButton = document.querySelectorAll(".change");
Array.from(readButton).forEach((element) => {
element.addEventListener("click", changeRead);
});
async function changeRead() {
try {
const response = await fetch("changeRead", {
method: "put",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
read: "false",
}),
});
const data = await response.json();
console.log(data);
// location.reload();
} catch (error) {
console.log(error);
}
}
Node.js: side note: I've changed the title: request.body.title to read:request.body.read, same issue.
app.put("/changeRead", (request, response) => {
db.collection("books")
.updateOne(
{ title: request.body.title },
{
$set: {
read: "false",
},
}
)
.then((result) => {
console.log("read changed");
response.json("book status changed");
})
.catch((error) => console.log(error));
});
index.ejs
<% for(let i=0; i<books.length; i++) {%>
<div class="col-sm-6 col-md-4 col-lg-3 text-center">
<div class="card book">
<div class="row">
<div class="col-1 binding p-0 <%= books[i].read %>" id="<%= books[i].read %>"></div>
<div class="col-10 p-0">
<div class="card-body p-4">
<h5 class="cart-title p-2">
<%= books[i].title %>
</h5>
<p class="card-text"><%= books[i].author %>
</p>
<p class="card-text">Pages: <%= books[i].pages %>
</p>
<p class="card-text">Published: <%= books[i].published %>
</p>
<button type="button" class="btn text-center change m-1">Change Read
</button>
<button type='button' class="btn text-center delete my-1">Delete Book
</button>
</div>
</div>
</div>
</div>
</div>
<%}%>
Example MongDB document:
_id : redacted
title : "The Return of the Kings"
author : "J.R.R. Tolkien"
pages : "416"
published : ""
read : "true"
I can post full code too if need be.