How to display specific data in ejs from mongoose? - node.js

I am new to NodeJS and MongoDB .I want to specific data from my database using mongoose . Those specific data are decided by a searchIndex and searchValue which is provided as a post request
The ejs page which provides the searchIndex and searchValue
<form action="/searchDetails" method="post">
<table>
<tr>
<td>
Select Search Category:
</td>
<td>
<select name="searchIndex">
<option>Name</option>
<option>Rollno</option>
<option>Branch</option>
<option>Hostel</option>
<option>RoomNo</option>
<option>ContactNo</option>
<option>Semester</option>
<option>FName</option>
<option>MName</option>
<option>Address</option>
</select>
</td>
</tr>
<tr>
<td>Enter the Search Value:</td>
<td><input type="text" name="searchValue"></td>
</tr>
<tr>
<td><input type="Submit" name="Search"></td>
</tr>
</table>
</form>
This is my mongoose schema
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
username: String,
password: String,
});
var studentSchema=new mongoose.Schema({
Name:String,
Rollno:String,
Branch:String,
Hostel:String,
RoomNo:String,
ContactNo:String,
Semester:String,
FName :String,
MName:String,
Address:String,
});
mongoose.model('Students3', studentSchema);
mongoose.model('User', userSchema);
this is my server.js
router.post('/searchDetails', function(req, res, next) {
var searchIndex=req.body.searchIndex;
var searchValue=req.body.searchValue;
students.find({searchIndex:searchValue},function(err,data){
if(err)
{
console.log(err);
}
else if(!data)
{
console.log('no data');
res.redirect('/homepage');
}
else
{
console.log(data);
output=data;
res.redirect('/editStudents')
router.get('/editStudents',function(req,res,next){
res.render('editStudents',{output});
});
}
});
});
this is my ejs where i display the value
<table border="1">
<tr>
<td>
<i>Name</i>
</td>
<td>
<i>Rollno</i>
</td>
<td>
<i>Branch</i>
</td>
<td>
<i>Hostel</i>
</td>
<td>
<i>RoomNo</i>
</td>
<td>
<i>ContactNo</i>
</td>
<td>
<i>Semester</i>
</td>
<td>
<i>Father's Name</i>
</td><td>
<i>Mother's Name</i>
</td><td>
<i>Address</i>
</td>
</tr>
<%
output.forEach(function(name)
{
%>
<tr>
<td><%=name.Name%></td>
<td><%=name.Rollno%></td>
<td><%=name.Branch%></td>
<td><%=name.Hostel%></td>
<td><%=name.RoomNo%></td>
<td><%=name.ContactNo%></td>
<td><%=name.Semester%></td>
<td><%=name.FName%></td>
<td><%=name.MName%></td>
<td><%=name.Address%></td>
</tr>
<%
})
%>
</table>
But the problem is it doesnot display any data.please help

Related

handlebars.js build in helper #each not working

I am using expressjs and mongoose in backend and handlebars as view engine.
Here is my method in index js
const router = require('express').Router()
const Product = require('../../models/Products')
// Products
router.get('/products',async (req, res) => {
try{
const products = await Product.find()
res.status(200).render('products',{products})
}catch(err){
res.status(400).render('products')
}
})
Documents inside product collection is like this:
[
{
_id: new ObjectId("632d74a0b828b58a1d25b047"),
title: 'Footballs',
description: 'This is a nice product.',
images: [
'/product-images/1663923360491/image1.png',
'/product-images/1663923360491/image2.png'
],
categories: [ 'football', 'balls', 'sports' ],
price: 800,
stock: 300,
createdAt: 2022-09-23T08:56:00.546Z,
updatedAt: 2022-09-23T08:56:00.546Z,
__v: 0
}
]
And here is the foreach sentence at index.hbs
<table>
<thead>
<tr>
<td>Date</td>
<td>Product</td>
<td>Price</td>
<td>Options</td>
</tr>
</thead>
<tbody>
{{#each products}}
<tr>
<td>{{this.createdAt}}</td>
<td>{{this.title}}</td>
<td>₹{{this.price}}</td>
<td>
<button>edit</button>
<button>delete</button>
</td>
</tr>
{{/each}}
</tbody>
</table>
This code is not working (td tag is empty). But when I put {{#index}},the index of the current array item is displaying but other values are not displaying.
{{#each products}}
<tr>
<td>{{#index}}</td>
<td>{{this.title}}</td>
<td>₹{{this.price}}</td>
<td>
<button>edit</button>
<button>delete</button>
</td>
</tr>
{{/each}}
Any help is greatly appreciated, thanks in advance!
You don't need to use this here:
{{#each products}}
<tr>
<td>{{createdAt}}</td>
<td>{{title}}</td>
<td>₹{{price}}</td>
<td>
<button>edit</button>
<button>delete</button>
</td>
</tr>
{{/each}}
If using mongoose, this issue can be solved by using .lean() to get a json object (instead of a mongoose one):
const products = await Product.find().lean()
res.status(200).render('products',{products})

Express.js - Posted data not rendering until refresh the page

I am send and fetch data from MySql Database with Express.js and Sequelize.js. All my code works correctly. My problem is, posted data not rendering on the Handlebars template until refresh the page. I also tried res.render method after SaveSettings method but don't worked. I want to render updated data after redirect.
Solved
You're missing return before settings.update(). Without it, the SaveSettings promise resolves before the update has completed - #Phil
function SaveSettings(Model, values) {
return Model.findByPk(1).then((settings) => {
if (!settings) {
return Model.create(values).catch((e) => console.log(e));
} else {
return settings.update(values).catch((e) => console.log(e));
}
});
}
Routes
router.get("/admin", csrf, isAuth, controller.getGeneral);
router.post("/admin", isAuth, controller.postGeneral);
Controllers
exports.getGeneral = (req, res) => {
Models.General.findByPk(1).then((result) => {
return res.render("dashboard/index", {
title: "General Settings",
data: result,
});
});
};
exports.postGeneral = (req, res) => {
SaveSettings(Models.General, req.body)
.then(() => res.redirect("/admin"));
};
SaveSettings Method
function SaveSettings(Model, values) {
return Model.findByPk(1).then((settings) => {
if (!settings) {
return Model.create(values).catch((e) => console.log(e));
} else {
settings.update(values).catch((e) => console.log(e));
}
});
}
Frontend
<form action="" method="post" class="table-responsive">
<input type="hidden" name="_csrf" value="{{csrfToken}}" />
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-success">Save</button>
</div>
<table class="table table-striped table-sm mt-3">
<thead>
<tr>
<th scope="col">Slot</th>
<th scope="col">Value</th>
</tr>
</thead>
<tbody>
<tr>
<td class="align-middle">Name</td>
<td class="align-middle">
<input
name="name"
class="form-control"
type="text"
value="{{data.name}}"
/>
</td>
</tr>
<tr>
<td class="align-middle">Description</td>
<td class="align-middle">
<input
name="description"
class="form-control"
type="text"
value="{{data.description}}"
/>
</td>
</tr>
<tr>
<td class="align-middle">Email</td>
<td class="align-middle">
<input
name="email_address"
class="form-control"
type="email"
value="{{data.email_address}}"
/>
</td>
</tr>
</tbody>
</table>
</form>

Nodejs - MongoDB Query

I have a little problem with my Thesis project.
I have a mongodb database with abour 400k entries styled like this:(i've translated the variables so if theres any typo, sorry);
var mongoose = require("mongoose");
var work_schema = new mongoose.Schema({
worktype: String,
ordernumber: String,
art_code: String,
qta: String,
number_of_operatos: String,
1_op_code: String,
2_op_code: String,
3_op_code: String,
4_op_code: String,
phase: String,
notes: String,
continued: String, //just a flag
date_start: String, // DD-MM-YYYY
date_end: String, // DD-MM-YYYY
time_start: String, //HH:MM:SS
time_end: String, //HH:MM:SS
datainiziopart: String, //this is the date parsed like this YYYYMMDD i needed it for another purpose
datafinepart: String, //this is the date parsed like this YYYYMMDD i needed it for another purpose
cronsec: String,
cronsec1: String,
cronsec2: String,
cronsec3: String,
cronsec4: String,
cronsec5: String,
cronsec6: String,
cronsec7: String,
operationtimesec: String,
designtimesec: String,
totalecausalisec: String,
ke: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String,
codicereparto: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Reparti"
},
nomereparto: String,
descrizionereparto: String
}
}
});
module.exports = mongoose.model("Work", work_schema);
As you can see the schema is not small at all, and having more than 400k entries, i need to query them when exporting/showing.
I used the limit function to show the latest entries.
I want to create a Page with a datepicker to query the data, or using the
date_start: String, // DD-MM-YYYY
or using the
datainiziopart // YYYYMMDD like <>=
Can you help me write the nodejs code to render a page with the result?
I use express if that can help.
i tried to do this
router.get("/risultati", function(req, res) {
Request.getAllRequestListingsCb(function (err, docs){
res.render('pannello/risultati', { rL: docs });
});
});
router.post("/ricercautente", function(req, res) {
var data = req.body.filtro;
var datadivisa = data.split(' - ');
var datestart= moment(datadivisa[0], 'DD-MM-YYYY').format('DD-MM-YYYY');
var dateend= moment(datadivisa[1], 'DD-MM-YYYY').format('DD-MM-YYYY');
//res.redirect("/pannello/utentetutti");
module.exports.getAllRequestListings = function (callback) {
var query = {"datainizio": {"$gte": new Date(datainizio), "$lt": new Date(datafine)}};
Lavori.find(query, callback);
};
res.redirect('pannello/risultati');
});
<div class="" align=center>
<form action="/ricercautente" method="post">
<input type="text" name="filtro" id="filtro" />
<button class="pure-button pure-button-warning" name="" id="" type="submit">Submit</button>
</form>
</div
and on another page
<tbody>
<% lavoritrovati.forEach(function(lavoro){ %>
<tr>
<td> <%=lavoro.author.codicereparto.nomereparto%> </td>
<td> <%=lavoro.tipodilavoro%> </td>
<td> <%=lavoro.ordineproduzione %> </td>
<td> <%=lavoro.codicearticolo %> </td>
<td> <%=lavoro.quantita %> </td>
<td> <%=lavoro.noperatori %> </td>
<td> <%=lavoro.codoperatori%> </td>
<td> <%=lavoro.codoperatori2%> </td>
<td> <%=lavoro.codoperatori3%> </td>
<td> <%=lavoro.codoperatori4%> </td>
<td> <%=lavoro.fase %> </td>
<td> <%=lavoro.note %> </td>
<td> <%=lavoro.datainizio %> </td>
<td> <%=lavoro.timestart %> </td>
<td> <%=lavoro.datafine %> </td>
<td> <%=lavoro.timeend %> </td>
<td> <%=lavoro.continuato %> </td>
<td> <%=lavoro.cronsec %> </td>
<td> <%=lavoro.cronsec1 %> </td>
<td> <%=lavoro.cronsec2 %> </td>
<td> <%=lavoro.cronsec3 %> </td>
<td> <%=lavoro.cronsec4 %> </td>
<td> <%=lavoro.cronsec5 %> </td>
<td> <%=lavoro.cronsec6 %> </td>
<td> <%=lavoro.cronsec7 %> </td>
<td> <%=lavoro.designtimesec %> </td>
<td> <%=lavoro.operationtimesec %> </td>
<td> <%=lavoro.ke %> </td>
<% }); %>

Data is not render into EJS page

I am looking for a solution for my EJS template. I am working on a project and I have completed about 50% of it. Currently I am working on a web page where I have to display the SQL data into EJS web template.
I have posted my coding which is i am working on it.
data is receiving from database (I checked with console.log and I posted the Json out put).
I tried all the possible ways to work it out but I did not get the result. It would be great if someone could help me..
Thanks in advance.
/* app.js */
app.get('/data', receiveData);
function receiveData(req, res)
{
db.executeSql("SELECT * FROM arduino", function (recordsets, err, ) {
var data = JSON.stringify(recordsets);
if (err) {
httpMsgs.show500(request, res, err);
}
else {
var Jdata = JSON.parse(data);
res.render('arduino',{Jdata:Jdata});
console.log(data);
}
});
}
/* arduino.ejs */
<html>
<head>
<body>
<div class="page-data">
<div class="data-table">
<table border="1" cellpadding="7" cellspacing="7">
<tr>
<th> - </th>
<th>ID</th>
<th>Machine</th>
<th>Start Time</th>
<th>End Time</th>
<th>Length Time</th>
<th> Day/Night</th>
<th>Job Number</th>
</tr>
<% if(Jdata.length){
for(var i = 0;i < Jdata.length;i++) { %>
<tr>
<td><%=(i+1)%></td>
<td> </td>
<td><%=Jdata[i].Machine%></td>
<td><%=Jdata[i].StartTime%></td>
<td><%=Jdata[i].EndTime%></td>
<td><%=Jdata[i].LengthTime%></td>
<td><%=Jdata[i].Day%></td>
<td><%=Jdata[i].ID %></td>
<td><%=Jdata[i].JobNumber %></td>
</tr>
<% }
}else{ %>
<tr>
<td colspan="3">No Data</td>
</tr>
<% } %>
</table>
</div>
</div>
</body>
</head>
</html>
{"recordsets":[[{"ID":1,"Machine":"TRUMPF 5000","StartTime":"2018-11-01T15:28:51.000Z","EndTime":"2018-11-01T15:52:11.000Z","LengthTime":271,"Day":"Day","JobNumber":null}]]

Javascript function not defined when called on input onclick()

I keep getting a
ReferenceError: del is not defined.
Before it was working where it would refresh the page, but I set it up so that it would only refresh the div when clicking.
while($row = $result->fetch_assoc()) {
$fileID = $row['fileID'];
echo "<tbody><tr>";
echo "
<td bgcolor='white'>
<input type='checkbox' checked>
</td>
<td bgcolor='white'>
{$row['name']}
</td>
<td bgcolor='white'>
{$row['type']}
</td>
<td bgcolor='white'>
{$row['size']}
</td>
<td bgcolor='white'>
{$row['created']}
</td>
<td>
<input type='button' name='download' value='Download' onclick='window.location="get_file.php?fileID=$fileID";'>
</td>
<td>
<script type='text/javascript'>
function del() {
console.log('Im working!');
var r = confirm('Do you want to remove this file?');
if (r == true) {
$.ajax({url: 'delete.php',
data: {action: '<?php print $fileID;?>'}
type: 'post';
success: function() {
$('#fileTable').load(document.URL + ' #fileTable');
}
});
}
}
</script>
<input type='button' name='delete' value='Delete' onclick='del()'>
</td>
You're duplicating your function for every row, and when you press a button, the function does not know what ID you're after.
Change it to something like:
echo <<<EOHTML
<script type='text/javascript'>
function del(id) {
console.log('Im working!', id);
var r = confirm('Do you want to remove this file?');
if (r == true) {
$.ajax({url: 'delete.php',
data: {action: id.toString()}
type: 'post';
success: function() {
$('#fileTable').load(document.URL + ' #fileTable');
}
});
}
}
</script>
EOHTML;
while($row = $result->fetch_assoc()) {
$fileID = $row['fileID'];
echo <<<EOHTML
<tbody><tr>
<td bgcolor='white'>
<input type='checkbox' checked>
</td>
<td bgcolor='white'>
{$row['name']}
</td>
<td bgcolor='white'>
{$row['type']}
</td>
<td bgcolor='white'>
{$row['size']}
</td>
<td bgcolor='white'>
{$row['created']}
</td>
<td>
<input type='button' name='download' value='Download' onclick='window.location="get_file.php?fileID={$fileID}";'>
</td>
<td>
<input type='button' name='delete' value='Delete' onclick='del({$fileID})'>
</td>
EOHTML;
}

Resources