How to delete the multiple rows based on checkbox conditon - node.js

I am new to node.js. I am created small example, now I want to delete multiple rows based on checkbox condition. I have one table of checkboxes as last column. I want delete checked checkbox rows when click on button.
Jade code is
<section class="get">
<h3>Get Data</h3>
LOAD DATA
<div>
<table>
{{# each items }}
<article class="item">
<tr>
<td>{{ this.title }}</td>
<td>{{ this.content }}</td>
<td>{{ this.author }}</td>
<td>{{ this._id }}</td>
<form action="/check" method="post">
<td><input type="checkbox" id="chk" name="chk" ></td>
</article>
</tr>
{{/each}}
<button>check</button>
</form>
</table>
</td>
</section>
Back end code is
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('user-data').find();
cursor.forEach(function(doc, err) {
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close();
res.render('index', {items: resultArray});
});
});
});`
router.post('/check', function(req, res, next) {
// var id = req.body.id;
console.log("check value");
console.log(req.body.chk);
req.body.chk=Boolean(req.body.chk);
for(i=0; i<req.body.chk;i++){
if(req.body.chk==true){
res.redirect('/');
}
else{
res.send("checkbox is not checked");
}
}
});

Related

How to work out with sending sms using nexmo in nodejs?

This is the route code:
router.get('/compose/:ID', function(req, res, next) {
var random = Math.floor((Math.random() * 1000000) + 1);
console.log("random = " + random);
res.render('compose', { random: random, Id:req.params.ID });
})
.post(function(req, res, next) {
var to = '917985754084';
var from = 'GrumpyText';
var text = req.body.OTP;
console.log(text);
nexmo.message.sendSms(from, to, text, function(err,success){
if(success)
console.log("SMS sent successfully!");
else {
console.log("error");
}
});
});
This is the handlebar code:
<main role="main" class="container">
<div class="jumbotron">
<h1>List of Contacts</h1>
<table class="table table-striped">
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<form method="post" enctype="multipart/form-data">
<tr>
<td><input type="text" name="OTP" class="form-control" value="Hi. Your OTP is : {{random}}"></td>
<td></td>
</tr>
<tr>
<td><button type="submit" class="btn btn-lg btn-primary btn-block">Submit</button>
</td>
</tr>
</form>
</tbody>
</table>
</div>
</main>
Its coming to the route but the console is not printing the 'text'. aka console.log(text) means req.body.OTP is not printing anything. Earlier it was printing undefined.
Could you please rectify where it is stucking perhaps?
The issue you are hitting is body-parser doesn't handle multipart/form-data.
There are several options, but one of those is multer.
\* add these for multi-part*\
var multer = require('multer')
var upload = multer();
\* other code *\
router
.get('/compose/:ID', function (req, res, next) {
var random = Math.floor(Math.random() * 1000000 + 1);
console.log('random = ' + random);
res.render('compose', { random: random, Id: req.params.ID });
})
.post('/compose/:ID', upload.none(), function (req, res, next) {
var to = '917985754084';
var from = 'GrumpyText';
var text = req.body.OTP;
nexmo.message.sendSms(from, to, text, function (err, success) {
if (success) console.log('SMS sent successfully!');
else {
console.log('error');
}
});
});

Get saved data from MongoDB collection and use it in code on button click [Node JS express]

I have an code in NodeJS which stores data in collection specific to the user.
This the router to GET and POST the data from EJS form.
server.get('/changeaccounts', async (req, res) => {
try{
const accounts = await account.find({user: req.user.id}).lean()
res.render("backend/changeaccounts", {
name: req.user.name,
accounts
});
} catch(err) {
console.log(err)
}
})
server.post('/changeaccounts', async (req, res) => {
try{
req.body.user = req.user.id
await account.create(req.body)
res.redirect('/dashboard')
}catch(err) {
console.log(err)
}
})
This sends the data entered from the form to the collection specific to every logged in user(included in the attached image)
Here is the image for database
I have an forEach loop going in the EJS template
<% if (accounts) {%>
<table class = "striped">
<thead>
<tr>
<th>Account</th>
<th>Select Account</th>
</tr>
</thead>
<tbody>
<% accounts.forEach(accounts => { %>
<tr>
<td><%= accounts.title%></td>
<td><button type="submit" id="buttonforaccount" class = "btn btn-primary col-auto" >Use this account</button></td>
</tr>
<%});%>
</tbody>
</table>
<%} else {%>
<p>You have no accounts added</p>
<% } %>
The output is given in the second attached image.
This is the image for the table output
What I want to do is when the Button is clicked by the user, it fetches the title and password (as shown in first image) from the collection and is usable through my code as follows.
control.post('/like', (req, res, next) => {
let tags = req.body.likes;
let title = From the collection on button click //title here
let password = from the collection on button click //password here
iglike(title, password, tags);
next();
res.send(title);
res.send(password);
res.send(tags);
});

Data is not displaying nodejs handlebars

I am trying to display data from my database but it doesnt seem to show up, what I did is followed a tutorial for this on ejs and it seemed to work fine and I am now trying it on handlebars
app.get('/', function(req, res, next) {
req.db.collection('users').find().sort({"_id": -1}).toArray(function(err, result) {
if (err) {
req.flash('error', err);
res.render('user/list', {
title: 'Users List',
data: ''
});
} else {
res.render('user/list', {
title: 'Users List',
data: result
});
}
});
});
<table class="table table-striped">
<tr>
<th>Name</th>
<th>Type</th>
<th>Desciption</th>
<th>Action</th>
</tr>
{{#if user}}{{#each user}}
<tr>
<td>{{this.Name}}</td>
<td>{{this.Type}}</td>
<td>{{this.Description}}</td>
<td>
<div style="float:left">
<a href='/users/edit/{{ user._id}}'>Edit</a>
<form method="post" action="/users/delete/{{user._id}}" style="float:right">
<input type="submit" name="delete" value='Delete' onClick="return confirm('Are you sure you want to delete?')" />
<input type="hidden" name="_method" value="DELETE" />
</form>
</div>
</td>
</tr>
{{/each}}{{/if}}
</table>
This is the ejs project that I made by following a tutorial and it currently is working
<table width='80%' border=0>
<tr style='text-align:left; background-color:#CCC'>
<th>Name</th>
<th>Type</th>
<th>Description</th>
<th>Action</th>
</tr>
<!--
Using FOREACH LOOP for the users array
myArray.forEach(function(el, index) {
// el - current element, i - index
});
-->
<% if (data) { %>
<% data.forEach(function(user){ %>
<tr>
<td><%= user.Name %></td>
<td><%= user.Type %></td>
<td><%= user.Description %></td>
<td>
<div style="float:left">
<a href='/users/edit/<%= user._id %>'>Edit</a>
<form method="post" action="/users/delete/<%= user._id %>" style="float:right">
<input type="submit" name="delete" value='Delete' onClick="return confirm('Are you sure you want to delete?')" />
<input type="hidden" name="_method" value="DELETE" />
</form>
</div>
</td>
</tr>
<% }) %>
<% } %>
</table>
app.get('/', function(req, res, next) {
// fetch and sort users collection by id in descending order
req.db.collection('benefits').find().sort({"_id": -1}).toArray(function(err, result) {
if (err) {
req.flash('error', err);
res.render('user/list', {
title: 'User List',
data: ''
});
} else {
res.render('user/list', {
title: 'User List',
data: result
});
}
});
});
I just tried to convert the ejs code to handle bars with some reasearch on how it works but it did not turn out my way
I am still a beginner in using nodejs so please go easy on me
Not only you have to convert your templates from ejs to handlebars, but you also have to use handlebars middleware with express.
Here you will find one : https://www.npmjs.com/package/express-handlebars
Install it with, for example npm : npm install --save express-handlebars
Then, declare it in your server file :
var exphbs = require('express-handlebars');
var app = express();
Edit:
I see that you use a kind of 'partials' to render your users' list page, so you have to declare its path :
var hbs = exbphbs.create({
defaultLayout: 'main',
partialsDir: 'views/partials/',
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
Now your workspace should look like this :
app.js
views/
list.handlebars
layouts/
main.handlebars
partials/
user/
list.handlebars
In your template, you check the presence of a user var, so you have to name it in the render function, instead of data:. Plus, render the file list.handlebars
app.get('/', function(req, res, next) {
req.db.collection('users').find().sort({"_id": -1}).toArray(function(err, result) {
if (err) {
req.flash('error', err);
res.render('list', {
title: 'Users List',
user: '',
});
} else {
res.render('list', {
title: 'Users List',
user: result,
});
}
});
});
views/list.handlebars :
{{> user/list}}
views/layouts/main.handlebars
<!DOCTYPE html>
<html>
<head>
</head>
<body>
{{body}}
</body>
</html>
views/partials/user/list.handlebars : notice i removed this. and user.
<h1>{{title}}</h1>
<table class="table table-striped">
<tr>
<th>Name</th>
<th>Type</th>
<th>Desciption</th>
<th>Action</th>
</tr>
{{#if user}}
{{#each user}}
<tr>
<td>{{Name}}</td>
<td>{{Type}}</td>
<td>{{Description}}</td>
<td>
<div style="float:left">
<a href='/users/edit/{{ _id}}'>Edit</a>
<form method="post" action="/users/delete/{{_id}}" style="float:right">
<input type="submit" name="delete" value='Delete' onClick="return confirm('Are you sure you want to delete?')" />
<input type="hidden" name="_method" value="DELETE" />
</form>
</div>
</td>
</tr>
{{/each}}
{{/if}}
</table>

How to do delete operation in database using checkbox?

I tried to delete multiple items from database using check box using node.js.But if any one of the check box is true everything is true.How to get this?
here the checkbox value for each item is not getting passed.
how to solve this.
router.post('/del', function (req, res, next) {
mongo.connect(url, function (err, db) {
assert.equal(null, err);
var cursor = db.collection('log').find();
cursor.forEach(function (doc, err) {
var id2 = Boolean(req.body.chk);
db.collection('log').findAndModify({ "option": id2 }, function (err, result) {
if (result) {
assert.equal(null, err);
console.log('Item updated');
resultArray4.push(id2);
console.log(resultArray4);
var id3 = id2;
id2 = null;
db.collection('log').deleteMany({ "option": id3 }, function (err, result) {
assert.equal(null, err);
console.log('Item deleted');
});
} else {
res.render('check');
}
});
});
}); res.render('check');
resultArray4.length = 0;
id2 = id3 = null; count = 0;
});
Handlebars code ....here the checkbox value for each item is not getting passed.
how to solve this.
<div class="deletedd">
<table class="table-table-bodered" border="auto" style="solid">
<th>Title</th>
<th>Content</th>
<th>Author</th><br><br>
<th>Select</th>
<div>
{{#each items }}
<tr>
<article class="item">
<td>{{ this.name }}</td>
<td>{{ this.number }}</td>
<td>{{ this.address }}</td>
<td>
<form action="/checkss/del" method="post"><input type="checkbox" name="chk"></td>
</article>
</tr>
{{/each}}
</div>
</table>
</div>
<button type="submit">delete</button>
</form>

Set input field value with data from mongoose

Hi,
I'm trying to get value from mongoose and populate textbox with it. So basically when I click Edit button I would like the name of the department appear in Department name textbox. I tried multiple things but failed. ($('#departmentName').val(department.name) for example) How can I do it properly? Thank you.
my department handlebar
<h2>Departments List</h2>
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<form method="POST" action="/departments/create_department">
<td><input class="form-control" type="text" placeholder="Department Name" name="departmentName" id="departmentName"></td>
<td><button class="btn btn-primary" type="sumit">Add Department</button></td>
</form>
<td><button class="btn btn-info">Update</button></td>
<td><button class="btn btn-info">Clear</button></td>
</tr>
{{#each departments}}
<tr>
<form method="POST" action="/departments/remove_department/{{_id}}?_method=DELETE">
<td>{{name}}</td>
<td><button class="btn btn-danger" type="submit">Remove</button></td>
</form>
<form method="GET" action="/departments/edit_department/{{_id}}?">
<td><button class="btn btn-warning" value={{id}} type="submit">Edit</button></td>
</form>
</tr>
{{/each}}
</tbody>
</table>
</div>
</div>
my department controller
var express = require('express');
var router = express.Router();
var passport = require('passport');
var mongoose = require('mongoose');
var Departments = require('../models/department');
var User = require('../models/user');
// List of departments
router.get('/add_department', userAuthenticated, function(req, res, next) {
Departments.find(function(err, departments) {
if (err) {
throw err;
}
res.render('add_department', {title:'Add New Department', departments: departments, name: departments.name, id: departments._id})
})
});
// Edit department
router.get('/edit_department/:id', userAuthenticated, function(req, res, next) {
var departmentName = "";
Departments.findById(req.params.id).exec(function(err, department) {
if (err) {
throw err;
} else {
$('#departmentName').val(department.name);
res.redirect('/departments/add_department');
}
})
});
You could try changing the input field in handlebars to display the value you queried from mongoose
change this
<td><input class="form-control" type="text" placeholder="Department Name" name="departmentName" id="departmentName"></td>
to this
<td><input class="form-control" type="text" value={{name}} name="departmentName" id="departmentName"></td>
Then take this out of the routes
$('#departmentName').val(department.name);
UPDATE:
So something like this
// List of departments
router.get('/add_department', userAuthenticated, function(req, res, next) {
// grab the deparment from the req
var departmentFromEdit ="";
if(req.query.dn){
departmentFromEdit = req.query.dn;
}
Departments.find(function(err, departments) {
if (err) {
throw err;
}
res.render('add_department', {title:'Add New Department', departments: departments, name: departments.name, id: departments._id})
})});
// Edit department
router.get('/edit_department/:id', userAuthenticated, function(req, res, next) {
var departmentName = "";
Departments.findById(req.params.id).exec(function(err, department) {
if (err) {
throw err;
} else {
departmentName = encodeURI(department.name);
// dn for departmentName or defaultName
res.redirect('/departments/add_department?dn=' + departmentName);
}
})});

Resources