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
});
});
});
Related
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.
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 have a basic express project created. And I've created a file called lib/userhandler.js inside root folder.
//lib/userhandler.js
exports.addUser = function(req, res){
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var uName = req.body.username;
var uEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : uName,
"email" : uEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// If it worked, set the header so the address bar doesn't still say /adduser
//res.location("userlist");
// And forward to success page
res.redirect("userlist");
}
});
}
In my routs/users.js file, whenever the users page is loaded I want to send name and the mail values throught userhandler.js to the database.
//routes/users.js
var express = require('express');
var router = express.Router();
var User = require("../node_modules/SimpleExpress/routes/userhandler.js");
var name = "testuser6";
var mail = "testuser6#testdomain.com";
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
User.addUser(name, mail);
});
module.exports = router;
When I try to load users page it shows "Can't set headers after they are sent."
Thank You
You should try to return the error from your db to your route handler through a callback like this :
//routes/users.js
var express = require('express');
var router = express.Router();
var User = require("../node_modules/SimpleExpress/routes/userhandler.js");
var name = "testuser6";
var mail = "testuser6#testdomain.com";
/* GET users listing. */
router.get('/', function(req, res, next) {
User.addUser(name, mail, function(err, doc) {
if(err) {
res.send("There was a problem adding the information to the database.");
} else {
res.redirect("userlist");
}
});
});
//lib/userhandler.js
exports.addUser = function(name, mail, cb){
// Set our internal DB variable
var db = req.db;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : name,
"email" : mail
}, function (err, doc) {
cb(err, doc);
});
}
You shouldn't insert the request and response objects as parameters of the function addUser(). They should be in the router callback function. I added a new parameter to the function, so that you can pass the database as a parameter thanks to the router which receives the request object as a parameter.
//lib/userhandler.js
exports.addUser = function(uName, uEmail, db){
var collection = db.get('usercollection');
var result = true;
collection.insert({
"username" : uName,
"email" : uEmail
}, function (err) {
if (err) {
result = false;
}
});
return result; // true or false
}
I changed the code here also, so that the name and email variables can be received from the req and res parameters.
//routes/users.js
var express = require('express');
var router = express.Router();
var User = require("../node_modules/SimpleExpress/routes/userhandler.js");
//var name = "testuser6"; // I don't think you need this
//var mail = "testuser6#testdomain.com"; // and this
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
var db = req.db;
var name = req.body.username;
var mail = req.body.useremail;
if(!User.addUser(name, mail, db)) {
res.send("There was a problem adding the information to the database.");
return;
}
res.redirect('userlist');
});
module.exports = router;
I haven't tested the code because I really don't have time but I hope it works fine.
I am trying to build a checklist app that takes input from a form and then writes it to a collection. The problem is that, when I try to print the input on the same page I took it from, it does not reach the JavaScript in the html.
If I console.log(checklist_data);, I see all the data from mongo. How do I get it to the page?
routes/index.js:
//insert into the db ( works perfectly)
var mongoose = require('mongoose');
var checklist_model = mongoose.model('checklist_model');
exports.create = function (req, res) {
new checklist_model({
name: req.body.name,
comment: req.body.comment
}).save(function (err, checklist_model) {
res.redirect('/checklist');
});
// query db for all checklist items ( checklist_data has all the data )
exports.checklist = function (req, res) {
checklist_model.find(function (err, checklist_data, count) {
res.render('checklist', {
title: 'checklist',
checklist_data: checklist_data
});
console.log(checklist_data);
});
};
}
HTML:
//HTML code
<script language="javascript" class="lookhere">
checklist_data.forEach( function( checklist_model ){
checklist_model.content
});
</script>
app.js:
app.get('/', routes.index);
app.get('/checklist', routes.checklist);
app.post('/create', routes.create);
I'm trying to pull the number of documents in mongodb db and display it in my Application home page... I found this code that it works well but returns the list of all documents (users List):
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 }); }); });
I don't understand the part function(e,docs)!
I tried the following code to get the number of documents but it doesn't work:
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.count({},{},function(e,docs){
res.render('userlist', {
"userlist" : count }); }); });
Thank you for help
You can try for this:
You have to get the length from the callback docs..
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.length }); }); });