We are trying to retrieve data from mysql to display it in html/jade. Unfortunately we are not able to display the records on the HTML table.
Since we are using the mysql pool, things getting more difficult. Here is our code so far. (Uses skeleton build by express generator)
/models/bew.js
var mysql = require('mysql');
var pool = require('./databaseConnection');
var sorter = 'db.bew';
var sql = 'SELECT * FROM' + pool.escapeId(sorter);
var records = pool.query(sql, function(err, rows, fields) {
if (err) throw err;
// foreach
// for(row of rows){
// console.log(row);
// }
//console.log('The fields: ', rows[0].id);
});
module.exports = records;
(Comment out the for-of and console.log will print the SQL rows)
routes/index.js
var express = require('express');
var router = express.Router();
var records = require('../models/bew');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Bewerber',
records: records
});
});
module.exports = router;
views/index.jade (html would be better)
extends layout
block content
body
table#tblBewerber
thead
tr
th Name
th Status
th Letzte Änderung
th Datum
th Angelegt
th Nächster Schritt bis
th Nächster Schritt
th Zul. bearbeiten
th Bew. für
tbody
each record in records
tr
td=record.namen
We did several tests and it seems like the index.js doesn't get the data from 'bew.js'?
I broke it down a bit to make it easier to read.
This is how I'd solve it.
function sqlQuery( req, res, next ) {
pool.query("SELECT ...", function (err, rows) {
req.records = rows;
next();
})
}
router.get('/', sqlQuery, function(req, res, next) {
res.render('index', {
title: 'Bewerber',
records: req.records
});
});
This way you can split them in different files if that is what you were trying to achieve.
It seems like you can not seperate the express router and the sql query. This is the way it worked now for us:
routes/index.js
var mysql = require('mysql');
var express = require('express');
var router = express.Router();
var pool = require('../models/databaseConnection');
var sql = require('../models/bew');
router.get('/', function(req, res, next) {
pool.query(sql, function(err, rows, fields) {
if (err) throw err;
res.render('index', {
title: 'Bewerber',
records: rows
});
});
});
module.exports = router;
models/bew.js
var pool = require('./databaseConnection');
var sorter = 'bewerber.bewerber';
var sql = 'SELECT * FROM' + pool.escapeId(sorter);
module.exports = sql;
It would be nice to seperate them more we don't know a way how this could be possible.
Related
I am new to Node js and express. I trying to query my Azure database to get the list of patients(MR number). I am getting the list but I think the request.on() runs as an asynchronous function so first, it will render the HTML page without any list and after executing the function Node Js exit executing.
Code:
var express = require('express');
var router = express.Router();
//For database
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
function mrquery(connection) {
request = new Request(
"SELECT DISTINCT MRNO FROM Transaction_Record",
function(err, rowCount, rows) {
console.log(rowCount + ' row(s) returned');
process.exit();
}
);
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log(column.value);
});
});
connection.execSql(request);
}
/* GET home page. */
router.get('/', async function(req, res, next) {
var connection = req.app.get('connection');
var isconnected = req.app.get('isconnected');
if (isconnected) {
mrquery(connection)
res.render('index', {
title: 'Express'
});
} else {
console.log('Not Connected');
res.render('error', {
error: 'error'
});
}
});
module.exports = router;
Thanks in advance.
This is part of my code, and it doesn't work. It says,
ReferenceError: callback is not defined
at C:\js\kweb-hw\routes\board.js:14:13
var express = require('express');
var router = express.Router();
var mysql_db = require('../db/db_con')();
var pool = mysql_db.init();
/* GET home page. */
router.get('/', function(req, res, next) {
pool.getConnection(function (err,conn) {
if(err) {
if(conn) {
conn.release();
}
callback(err,null);
return;
}
var sql = "SELECT * FROM board";
var exec = conn.query(sql,[] ,function(err, rows) {
conn.release();
if (err) throw err;
res.render('board', { rows: rows });
});
});
});
You don't need a callback in this case, because you're at the end of your route, so to speak.
So instead, you could do something like handle it with sending an error message to your rendered page.
var express = require('express');
var router = express.Router();
var mysql_db = require('../db/db_con')();
var pool = mysql_db.init();
/* GET home page. */
router.get('/', function(req, res, next) {
pool.getConnection(function (err,conn) {
if(err) {
if(conn) {
conn.release();
}
res.render('board',{rows: [],error:'Could not connect'});
}else{
var sql = "SELECT * FROM board";
var exec = conn.query(sql,[] ,function(err, rows) {
conn.release();
if (err) throw err;
res.render('board', { rows: rows });
});
}
});
});
I am new in Node Js and trying to learn it. I am currently follow this tutorial: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ but its incomplete.
I want, if I click on any user from the list of users, it will take me to new page and show the record in form for update. I don't know how to send data onclick, find the record from the db and show it inside a form to update.
Here is the index file with all the functions:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*Get Hello world page*/
router.get('/helloword', function(req, res){
res.render("Helloworld", {title:'Hello, World!'});
});
/*Get UserList*/
router.get('/userlist', function(req, res){
var db = req.db;
var collection =db.get('usercollection');
collection.find({}, {}, function(e, docs){
res.render('userlist',{
"userlist": docs
});
});
});
/*Get New User Page*/
router.get('/newuser', function(req, res){
res.render('newuser',{title: 'Add New User'})
});
/* POST to Add User Service */
router.post('/adduser', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : userName,
"email" : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// And forward to success page
res.redirect("userlist");
}
});
});
module.exports = router;
Thanks in advance please help me for guidance
It looks like you want to use findAndModify (docs)
Using your code you could implement an update route like so.
router.post('/user/:userId', function (req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
collection.findAndModify(
{_id: req.query.userId}, // query
[['_id', 'asc']], // sort order
{
$set: {
"username": userName,
"email": userEmail
}
}, // replacement
{}, // options
function (err, object) {
if (err) {
console.warn(err.message); // returns error if no matching object found
} else {
console.dir(object);
}
});
});
However this does not have any validation to make sure that the user has the correct permissions to update this, make sure you add something like the query
{$and: [{_id: req.query.userId}, {createdBy: req.user}]}
I'm attemting to create an application to make restraunt reservations with Node, but currently my data from the database is not showing on the page. Here is the jade file of the page that is meant to display the data:
extends layout
block content
h1.
Reservations
ul
each reservation in reservations
li= reservation.lastName
li= reservation.numberOfPeople
Here is my index.js file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/reservations', function(req, res) {
var db = req.db;
var collection = db.get('freshStart');
collection.find({},{},function(e,docs){
res.render('reservations', {
"reservations" : docs
});
});
});
router.get('/makeReservation', function(req, res){
res.render('makeReservation', { title: 'Make a reservation'});
});
router.post('/makeReservation', function(req, res){
var db = req.db;
var lastName = req.body.lastName;
var numberOfPeople = req.body.numberOfPeople;
var time = req.body.myTime;
var date = req.body.myDate;
var collection = db.get('freshStart');
collection.insert({
"lastName" : lastName,
"numberOfPeople" : numberOfPeople,
"time" : time,
"date" : date
}, function(err, doc) {
if(err) {
res.send("There was a problem adding the information to the database", err.toString());
} else {
res.redirect("reservations");
}
});
});
module.exports = router;
Yet when I load the page, it only shows the title but no database info. I've queried the data in cmd and it comes up with two entries. What am I doing wrong?
The error was I was refrencing the wrong part of the database. This was my code:
router.get('/reservations', function(req, res) {
var db = req.db;
var collection = db.get('freshStart');
collection.find({},{},function(e,docs){
res.render('reservations', {
"reservations" : docs
});
});
});
What I should have been doing is this:
router.get('/reservations', function(req, res) {
var db = req.db;
var collection = db.get('reservations');
collection.find({},{},function(e,docs){
res.render('reservations', {
"reservations" : docs
});
});
});
I am new to MEAN stack. I am trying to retreive a list of documents from MongoDB. I have used Visual Studio 2013 community edition to create a basic Nodejs Express application. Visual studio created app.js file on the root for configuration. I have put following code in app.js which is relevant to mongodb:
var mongo = require('myDB');
var db = new mongo.Db("myDB", new mongo.Server("localhost", "27017"),
{ safe: true }, { auto_reconnect: true });
// Make our db accessible to our router
app.use(function (req, res, next) {
req.db = db;
next();
});
In the routes folder that visual studio created, I have created a js file which will perform CRUD operations. I have following code in this file:
var express = require('express');
var router = express.Router();
router.get('/myRecords', function (req, res) {
var db = req.db;
db.open(function (err, db) {
if (err)
console.log(err);
else {
var collection = db.collection('myCollection');
var dataToSend = collection.find();
res.send(dataToSend);
}
})
});
module.exports = router;
I am Type Error: Converting Circular structure to JSON.
I am trying to not using any schema.
Please advice.
For those of you, who encounter the similar problem, find() doesn't return the document, we need to use toArray to retrieve documents. Following code did the trick:
router.get('/myRecords', function (req, res) {
var db = req.db;
db.open(function (err, db) { // <------everything wrapped inside this function
db.collection('myCollection', function (err, collection) {
collection.find().toArray(function (err, items) {
res.send(items);
db.close();
});
});
});
});