Not being able to delete an item from to-do list using Item.removeOne( ) or Item.findByIdAndRemove( ) methods of mongoose in NodeJS - node.js

I am making a to-do list using mongodb,node.js,express and EJS. The part where I am stuck is I am not being able to delete and item from the list and the database. The idea is that on clicking a checkbox, the item beside will be deleted. Here is a layout for the same,
[https://i.stack.imgur.com/83gMW.png][1]
I made the necessary changes in my EJS file to create a "/delete" route as given below :
<%for(var i=0;i<taskslist.length;i++){%>
<form action="/delete" method="POST">
<div class="item">
<input type="checkbox" name="checkitem" value="<%= taskslist[i]._id %> " onChange="this.form.submit()">
<p><%= taskslist[i].activity %> </p>
</div>
</form>
<%}%>
In my app.js folder, I also made the necessary changes by using findByIdAndRemove( ) method for mongoose :
app.post("/delete", function (req, res) {
const delitem = req.body.checkitem;
Item.findByIdAndRemove(delitem, function (err) {
if (err) {
console.log("Error");
} else {
console.log("Succesfully deleted" + delitem);
res.redirect("/");
}
});
console.log(delitem);
});
However, the item is not getting deleted from the database and an error is showing in terminal, even though the console.log(delitem) is working and returning the id of the item whose checkbox is selected.
I am also giving a screenshot of the output I am getting at the terminal:
[https://i.stack.imgur.com/hGEkn.png][1]
All the methods related to adding items and creating database are working. I don't understand where the error is. Please help me out with this.

Related

Form Select onChange Sends Data/Info to Query on Server

I'm using Nodejs, Express, and EJS.
Here's what works...
I can use an unordered list of hyperlinks and send the info/variable via req.params this way...
db.ejs code
<ul>
<% dbTitle.forEach(function(dbTitle){ %>
<li><%= dbTitle.dbTitle %></li>
<% }) %>
</ul>
server.js code
app.get('/db/:dbTitle', async (req, res) => {
const {dbTitle} = req.params;
console.log(dbTitle);
try {
const tabTitleResult = await session.run(`MATCH (db:Database {Title: $dbTitle})-->(t:Table)-->(tv:TableVersion)
Where NOT (tv)<--(:InformationAsset)
RETURN db.Title as dbTitle, tv.Title as tabTitle Order By db.Title, tv.Title ASC`, {dbTitle});
const tabTitleArr = tabTitleResult.records.map(({_fields}) => {
return {dbTitle:_fields[0],tabTitle:_fields[1]};
});
res.render('table.ejs', { tabTitle: tabTitleArr});
//console.log(tabTitleArr)
} catch(e) {
console.log("Something went wrong", e)
}
});
everything from above displays nicely on this page...
table.ejs code
<table>
<tr>
<th>Database-Title</th>
<th>Table-Title</th>
</tr>
<% tabTitle.forEach(function (tabTitle){ %>
<tr>
<td><%= tabTitle.dbTitle %></td>
<td><%= tabTitle.tabTitle %></td>
<% }) %>
</tr>
</table>
Here's what doesn't work...
Instead of an unordered list of hyperlinks, I would prefer to have a dropdown select, however my code doesn't work when I try to use a form select option method to send the info/variable via req.body...
db.ejs code
<form method="post" action="/db">
<label>Database Name</label><br>
<select name="dbTitle" onchange="this.form.submit();">
<option selected disabled> -- select an option --
<% dbTitle.forEach(function(dbTitle){ %>
<option name="dbTitle" value="<%= dbTitle.dbTitle %>"><%= dbTitle.dbTitle %></option>
<% }) %>
</option>
</select>
</form>
(Note: I am aware of how strange the nested options seem, this is required to force the --select an option-- option to appear first, removing the nesting with only the one option with data does not help.
Also, you'll note that I'm adding name="dbTitle" on more than one element in a desperate attempt to make something work, I believe it should only be on the select element.
Last, I'm also trying to send any info/variable via value="<%= dbTitle.dbTitle %>.)
server.js code
app.post('/db/:dbTitle', async (req, res) => {
const {dbTitle} = req.body;
console.log(dbTitle);
try {
const tabTitleResult = await session.run(`MATCH (db:Database {Title: $dbTitle})-->(t:Table)-->(tv:TableVersion)
Where NOT (tv)<--(:InformationAsset)
RETURN db.Title as dbTitle, tv.Title as tabTitle Order By db.Title, tv.Title ASC`, {dbTitle});
const tabTitleArr = tabTitleResult.records.map(({_fields}) => {
return {dbTitle:_fields[0],tabTitle:_fields[1]};
});
res.render('table.ejs', { tabTitle: tabTitleArr});
//console.log(tabTitleArr)
} catch(e) {
console.log("Something went wrong", e)
}
});
From here, when I run and then select from the dropdown, I receive an error of Cannot POST /table, and nothing shows in my console.log(dbTitle);, so I'm assuming no variable is being sent from my form to the server.
From what I've gathered in using a form vs ul li hyperlinks, there are some differences where the form needs to have method="post", and the server needs to be app.post with req.body instead of req.params. Or maybe this is incorrect?
Thank you for any help you can share.
I figured it out, here's what I needed to do.
Everything was fine on my client db.ejs.
In my server.js, I needed to change app.post('/auradbtable/:dbTitle' to app.post('/auradbtable?:dbTitle'... change the '/' to '?'.
And using const {dbTitle}=req.body; is correct.

How to store and retrieve checkbox state on refresh of page? Mongoose/EJS/Nodejs/Express

I have a checkbox, essentially like a to do list. When i check the box, I want to retain the state even after i refresh the page by using mongoose. I do know of localstorage, however EJS runs on a server side. Currently I am able to post the checkbox to my express side.
IN EJS
form id="form2" action="/check" method="post"></form>
<input form="form2" type="checkbox" name="checkboxx" onChange="this.form.submit()">
IN EXPRESS
app.post("/check", function(req,res){
Item.updateOne({checked: req.body.checkboxx.checked}, function(err){
if(err){
console.log(err);
} else console.log("successfully updated db")
})
res.redirect("/")
})
My collection is "Item", the schema includes a boolean property "checked"
checkboxx is the name of the input checkbox.
Any way to update the information of the checkbox state and reload the saved states upon refreshing the page?
In my case, the user profile page is also a form for data entry. (I save the form values with mongoose on a Mongo Atlas db, so some steps are skipped here.)
In my profile.ejs page, the toggleswitch is :
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" name="onOffSwitch" id="onOffSwitch" <%= params.onOffSwitch ? "checked" : "" %> >
<label class="custom-control-label" for="onOffSwitch">Activate</label>
</div>
And in my Express app the route is :
app.post(`/api/params`, isLoggedIn, (req, res) => {
const email = req.user.email;
const onOffSwitch =req.body.onOffSwitch;
});
res.redirect(`/profile`);
});
Even after a log out and re-login, the checkbox value gets releaded correctly.

Checkbox value is refreshed after page reload in node JS

"I am creating TODO list using Node as backend. after adding every new item, a checkbox is also generating in front of them so I can apply "CSS line-through" to let user know that item is done or of no use. But when I add another item, the page refreshes and that checkbox is unchecked as I am not storing that value anywhere. Can you tell me how to store the value of that checkbox in the backend?
HTML -
<div class="box" >
<% for (var i=0; i<newListItems.length; i++) { %>
<div class="item">
<input type="checkbox" id="checkBox">
<p> <%= newListItems[i] %> </p>
</div>
<% } %>
<form action="/" method="post" class="item">
<input class="inputBox" type="text" name="newItem" placeholder="New item" autocomplete="off" required="required">
<button type="submit" name="list" value=<%= listTitle%>> +</button>
</form>
</div>
Node JS -
const items = [];
app.post("/", function(req, res){
let item = req.body.newItem;
items.push(item);
res.redirect("/");
});
The answer involves a lot of code, so I will give you a set of steps that can help in your case.
You need to change your data scheme. Currently looks like you are just storing the string in an array of items. You need to change it to be array of objects. Each object should have the field task and done. So you could know which task is done or not.
app.post("/", function(req, res) {
let item = req.body.newItem;
items.push({ name: item, done: false });
res.redirect("/");
});
Next step will be adding an endpoint that will be changing the done field of an array item to true.
Then on a front-end you will need to write some JS code that will be sending an HTTP request to the endpoint that marks the task as done. You need to use AJAX call for that, for example, NPM package axios.
Change the template to reflect the changes to the data. e.g. instead of <%= newListItems[i] %> do <%= newListItems[i].name %> and add logic to render checked checkbox based on done property.
It worth to mention, that you should not store data in memory, because once the process is done, you will lose your data. It is okay for learning purposes, but in production, you should use a database.

Cannot delete mongodb entry with node and handlebars

I tried various ways to delete a entry but no luck. I know I'm close. I did use "post" instead of "delete" with no luck. I did the action request on the html, no luck. Im in a pickle :(
My routers:
router.delete('/:id',function(req, res){
Docket.findById(req.params.id, function(err, docket){
docket.remove(function(err){
res.redirect('/dockets');
});
});
});
Handlebars:
<form name="create-docket-form" id="create-docket-form" method="post">
<div class="form-submit">
<input type="submit" name="delete" value="Delete my docket" />
</div>
</form>
In your form, you are using method method="post", but your route is listening for DELETE requests: router.delete('/:id',function(req, res){ So this router is never triggered because the app can't found the route.
I wonder, how do you send your requests, but in if you are using no JavaScript code, you can work around this by applying approach from this answer.
I did solve this problem, first, you have to change the "delete" to "get" in the "router.get()", after that, you go to HandleBars file and put a tag 'button' inside the tag '', put the 'href: '/adress/{{variable to delete}}', go to your node.js and prepare the route, now I'll show you my code:
NODE.EXPRESS / .JS:
app.get(`/del-comander/:comand`,express.json() ,(req,res)=>{
let comanderDel = req.params.comand
Comander.deleteOne({comander: comanderDel}).then(()=>{
console.log(`deleted: ${comanderDel}`)
res.redirect('back')
}).catch((err)=>{
res.send(err)
})
}),
HANDLEBARS:
{{#each comanders}}
<strong> comander: </strong>{{comander}} <br>
<strong> skill: </strong>{{skill}} <br>
<strong>season: </strong>{{season}} <br>
<a href='/del-comander/{{comander}}'><button>delete</button></a>
<br>
<hr>
{{/each}}
OBS: the args inside '{{}}' was connected with the DataBase, I also did more than just delete the data and printed it to the screen, so each data could be deleted separately, I do not know if my answer was good, but somebody else could have this same problem if you want more code just ask.

meteor get no data from second mongo database

iam total new at meteor and i try to build an Meteor application that should show the data another Mongo Database. The app it self can use its own metor database. So i found, that with MongoInternals.RemoteCollectionDriver() its to connect with my second database.
Next step is to make it work in the meteor tutorial. But i dont get back any data from the second database. For a test, simple arrays are returned correct from my function and placed right into the webapp. And the expression in .find() should be also ok. I tested it in the Mongo console.
If the connection to the second database is placed in if (Meteor.isClient) or outside of the client/server parts, the error "ReferenceError: MongoInternals is not defined" appears. If its set inside of if (Meteor.isServer) sometimes an exception appears in the console:
Exception in template helper: .ris_sessions#http://localhost:3000
/risdd_mongo.js?4fc7111851b4ed2182782e0a368b366cc4e89745:15:17
bindDataContext/<#http://localhost:3000/packages
/blaze.js?77c0809654ee3a10dcd5a4f961fb1437e7957d33:2693:14
...... and a lot more messages
I cant see, why dont getting back any data from the second database.
Here are the sources:
Tasks = new Mongo.Collection("tasks");
//////////////////////
if (Meteor.isClient) {
Template.body.helpers({
tasks: function() {
return Tasks.find({}, {sort: {createdAt: -1 }});
}
,
s_sessions: function() {
return ris_sess.find( {},{description:1} ).fetch();
}
});
}
//////////////////////
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
var risdb_drv = new MongoInternals.RemoteCollectionDriver("mongodb://172.0.0.1:27017/ris");
var ris_sess = new Mongo.Collection("sessions", { _driver: risdb_drv });
});
}
<head>
<title>foo</title>
</head>
<body>
<div class="container">
<header>
<h1>todo list</h1>
<!-- add a FORM !-->
<form class="new-task">
<input type="text" name="text" placeholder="ad your task here" />
</form>
</header>
<ul>
{{#each tasks}}
{{>task}}
{{/each}}
{{#each ris_sessions}}
{{>ris_session}}
{{/each}}
</ul>
</div>
</body>
<template name="task">
<li>{{text}}</li>
</template>
<template name="ris_session">
<li>{{description}}</li>
</template>
If you use local MongoDB server try change
mongodb://172.0.0.1:27017/ris
to
mongodb://127.0.0.1:27017/ris
Typo in IP: 127

Resources