Set input field value with data from mongoose - node.js

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);
}
})});

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');
}
});
});

How to get the radio button values from mongodb to the edit/update form? (Angular | Express | Nodejs | MongoDB)

Adding data to the database using this crud application successfully works. but when i'm trying edit a particular record (a document in mongodb), all the other fields get automatically filled with existing data in mongodb, but the radio button doesn't get selected according to the value stored in mongodb.
employee.component.html
<div class="row">
<div class="col s12">
<div class="card">
<div class="card-content white-text">
<div class="row">
<div class="col s5">
<form #employeeForm="ngForm" (ngSubmit)="onSubmit(employeeForm)">
<input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="employeeService.selectedEmployee._id">
<div class="row">
<div class="input-field col s12">
<input type="text" name="name" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.name" placeholder="Enter full name" required>
<label>Name :
<label class="red-text">*</label>
</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="text" name="position" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.position" placeholder="Eg : Snr. Developer">
<label>Position :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="text" name="office" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.office" placeholder="Enter office location">
<label>Office :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input type="text" name="salary" #name="ngModel" [(ngModel)]="employeeService.selectedEmployee.salary" placeholder="Salary per annum">
<label>Salary :</label>
</div>
</div>
<p>
<label>
<input name="gender" type="radio" value="1" [(ngModel)]="gender" />
<span>Male</span>
</label>
</p>
<p>
<label>
<input name="gender" type="radio" value="2" [(ngModel)]="gender"/>
<span>Female</span>
</label>
</p>
<div class="row">
<div class="input-field col s12">
<button class="btn btn-custom right" type="button" (click)="resetForm(employeeForm)">Reset</button>
<button class="btn btn-custom right" type="submit" [disabled]="!employeeForm.valid">Submit</button>
</div>
</div>
</form>
</div>
<div class="col s7">
<table class="responsive-table highlight">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th></th>
</tr>
</thead>
<tr *ngFor="let emp of employeeService.employees">
<td>{{emp.name}}</td>
<td>{{emp.position}}</td>
<td>{{emp.office}}</td>
<td>
<a class="action-btn" (click)="onEdit(emp)">
<i class="material-icons">edit</i>
</a>
<a class="action-btn" (click)="onDelete(emp._id,employeeForm)">
<i class="material-icons">delete</i>
</a>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
employee.component.ts
import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { EmployeeService } from '../shared/employee.service';
import { Employee } from '../shared/employee.model';
declare var M: any;
#Component({
selector: 'app-employee',
templateUrl: './employee.component.html',
styleUrls: ['./employee.component.css'],
providers: [EmployeeService]
})
export class EmployeeComponent implements OnInit {
constructor(private employeeService: EmployeeService) { }
ngOnInit() {
this.resetForm();
this.refreshEmployeeList();
}
resetForm(form?: NgForm) {
if (form)
form.reset();
this.employeeService.selectedEmployee = {
_id: "",
name: "",
position: "",
office: "",
salary: null,
gender: null
}
}
onSubmit(form: NgForm) {
if (form.value._id == "") {
this.employeeService.postEmployee(form.value).subscribe((res) => {
this.resetForm(form);
this.refreshEmployeeList();
M.toast({ html: 'Saved successfully', classes: 'rounded' });
});
}
else {
this.employeeService.putEmployee(form.value).subscribe((res) => {
this.resetForm(form);
this.refreshEmployeeList();
M.toast({ html: 'Updated successfully', classes: 'rounded' });
});
}
}
refreshEmployeeList() {
this.employeeService.getEmployeeList().subscribe((res) => {
this.employeeService.employees = res as Employee[];
});
}
onEdit(emp: Employee) {
this.employeeService.selectedEmployee = emp;
}
onDelete(_id: string, form: NgForm) {
if (confirm('Are you sure to delete this record ?') == true) {
this.employeeService.deleteEmployee(_id).subscribe((res) => {
this.refreshEmployeeList();
this.resetForm(form);
M.toast({ html: 'Deleted successfully', classes: 'rounded' });
});
}
}
}
employeeController.js
const express = require('express');
var router = express.Router();
var ObjectId = require('mongoose').Types.ObjectId;
var { Employee } = require('../models/employee');
// => localhost:3000/employees/
router.get('/', (req, res) => {
Employee.find((err, docs) => {
if (!err) { res.send(docs); }
else { console.log('Error in Retriving Employees :' + JSON.stringify(err, undefined, 2)); }
});
});
router.get('/:id', (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send(`No record with given id : ${req.params.id}`);
Employee.findById(req.params.id, (err, doc) => {
if (!err) { res.send(doc); }
else { console.log('Error in Retriving Employee :' + JSON.stringify(err, undefined, 2)); }
});
});
router.post('/', (req, res) => {
var emp = new Employee({
name: req.body.name,
position: req.body.position,
office: req.body.office,
salary: req.body.salary,
gender: req.body.gender,
});
emp.save((err, doc) => {
if (!err) { res.send(doc); }
else { console.log('Error in Employee Save :' + JSON.stringify(err, undefined, 2)); }
});
});
router.put('/:id', (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send(`No record with given id : ${req.params.id}`);
var emp = {
name: req.body.name,
position: req.body.position,
office: req.body.office,
salary: req.body.salary,
gender: req.body.gender,
};
Employee.findByIdAndUpdate(req.params.id, { $set: emp }, { new: true }, (err, doc) => {
if (!err) { res.send(doc); }
else { console.log('Error in Employee Update :' + JSON.stringify(err, undefined, 2)); }
});
});
router.delete('/:id', (req, res) => {
if (!ObjectId.isValid(req.params.id))
return res.status(400).send(`No record with given id : ${req.params.id}`);
Employee.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) { res.send(doc); }
else { console.log('Error in Employee Delete :' + JSON.stringify(err, undefined, 2)); }
});
});
module.exports = router;
This is the picture (https://imgur.com/82VbxBJ) of the current status of the edit form. I need this radio button to get selected according to the value stored in mongodb.
As you're using Angular, why don't you use Angular Material? MatRadioButton has a simple implementation.
<mat-radio-group
class="example-radio-group"
[(ngModel)]="selectedGender">
<mat-radio-button class="example-radio-button" *ngFor="let gender of listOfGenders" [value]="gender.displayValue">
{{gender.displayName}}
</mat-radio-button>
</mat-radio-group>
You can create a list of gender objects with displayName and displayValue properties in the ts file. Store the displayValue with the User Object in MongoDB. When you retrieve the data, assign the stored value to the selectedGender property.

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 delete the multiple rows based on checkbox conditon

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");
}
}
});

how to display data after form submit using expressjs

**app.js** Code
app.get('/', function (req, res) {
res.render('index', {
data: docsData,
title: "EJS example",
header: "Some users"
});
});
app.post('/', function (req, res) {
var jname= req.body.firstname;
var lname= req.body.lastname;
var jemail= req.body.email;
var collection = dbConnect.collection('users');
var document={name:jname, lastname:lname, email:jemail};
collection.insert(document, {w: 1}, function(err, records){
console.log("Record added as "+records[0]._id);
});
dbConnect.collection("users").find({"name":jname}).toArray(function(err, docsData) {
console.log('checking error',err, docsData);
res.render('index', {
data: docsData,
title: "AJT Family",
header: "Some users"
});
});
});
**html code**
<div align="center" ng-controller="FormCtrl">
<form name="form" ng-submit="submitForm()" novalidate>
<table>
<tr><td>Name:</td>
<td>
<input id="firstname" type="text" ng-model="regform.firstname" name="firstname" required="" />
</td>
<td>
<div ng-show="form.$submitted || form.firstname.$touched">
<div ng-show="form.firstname.$error.required">Enter your name.</div>
</div>
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
<input id="lastname" name="lastname" type="text" ng-model="regform.lastname" required>
</td>
<td>
<div ng-show="form.$submitted || form.lastname.$touched">
<div ng-show="form.lastname.$error.required">Enter your Last name.</div>
</div>
</td>
</tr>
<tr>
<td>E-mail:</td>
<td><input id="email" type="email" ng-model="regform.email" name="uEmail" required="" /></td>
<td>
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required">Enter your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
</td>
</tr>
</table>
<input type="button" ng-click="reset(form)" value="Reset" />
<input type="submit" ng-disabled="!form.$valid" value="Save" />
<p id="hu"></p>
</form>
</div>
<%if(data) {%>
<h1>Users</h1>
<% data.forEach(function(user){ %>
<br>
<table>
<tr><td>Name: </td><td><%= user.name %> <%= user.lastname %></td></tr>
<tr><td>Email: </td><td><%= user.email %></td></tr>
</table>
<% }) %>
<% } %>
</body>
</html>
**javascript**
var result;
var app = angular.module('formExample', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.data = {};
$scope.submitForm = function() {
formData = $scope.regform;
console.log("posting data....");
var request = $http({ url: '/',data: $scope.regform, method: 'post' });
console.log(formData);
};
});
here I can save data on mongodb using expressjs. I need to display data after form submission. Here nothing is displaying after form submission. How to display that saved content in html using embedded Javascript.
What you'll want to do is change your res.render() call to do something like this:
res.render('index', {
data: docsData,
title: 'AJT Family',
header: 'Some Users',
body: req.body, // This is your form data as a JSON object.
});
Then, in your index template, you'll have access to your form data to display however you want, if you're using Jade, for instance, you might want to say like:
h1 Data!
p #{body}

Resources