TheLearner TheLearner - 27 days ago 10
Javascript Question

Nodejs application crashes upon visiting form page

I am following along a Udemy tutorial. So far, everything was running fine until I connected the application to mongodb. The application runs fine, connects to the database but when I visit the form page, which is supposed to display data from the database, application crashes and gives me the following error.

app.js file



var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var appRoutes = require('./routes/app');

var app = express();
mongoose.connect('localhost:27017/node-angular2');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});

app.use('/', appRoutes);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
return res.render('index');
});


module.exports = app;





router/app.js



var express = require('express');
var router = express.Router();
var User = require('../models/user');

router.get('/', function (req, res, next) {

User.findOne({}, function(err, doc) {
if (err) {
return res.send('Error!');
}
res.render('node', {email: doc.email});
});
});

router.post('/', function(req, res, next) {
var email = req.body.email;
var user = new User({
firstName: 'Max',
lastName: 'Schwarz',
password: 'super-secret',
email: this.email
});
user.save();
res.redirect('/');
});

module.exports = router;





Error Log

> node ./bin/www

events.js:160
throw er; // Unhandled 'error' event
^

TypeError: Cannot read property 'email' of null
at /Users/farooqkhan/Documents/Udemy/node-angular2/routes/app.js:11:39
at Query.<anonymous> (/Users/farooqkhan/Documents/Udemy/node-angular2/node_modules/mongoose/lib/model.js:3381:16)
at /Users/farooqkhan/Documents/Udemy/node-angular2/node_modules/kareem/index.js:259:21
at /Users/farooqkhan/Documents/Udemy/node-angular2/node_modules/kareem/index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)

npm ERR! Darwin 16.1.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.9.1
npm ERR! npm v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! udemy-nodejs-angular2@1.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the udemy-nodejs-angular2@1.0.0 start script 'node ./bin/www'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the udemy-nodejs-angular2 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node ./bin/www
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs udemy-nodejs-angular2
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls udemy-nodejs-angular2
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/farooqkhan/Documents/Udemy/node-angular2/npm-debug.log


2nd Example.

Then I ran a mongodb IDE, I got from github. It used to work fine but now when I visit the homepage it also gives the following error:

> node app.js

(node:1054) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
adminMongo listening on host: http://0.0.0.0:1234
GET / 302 8.496 ms - 56
/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongodb/lib/mongo_client.js:237
throw err
^

TypeError: Cannot read property 'indexOf' of undefined
at module.exports (/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/parse-mongo-url/index.js:10:10)
at new Database (/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongojs/lib/database.js:43:20)
at module.exports (/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongojs/index.js:5:12)
at /Users/farooqkhan/Documents/mongoIDE/adminMongo/routes/index.js:58:22
at connectCallback (/Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongodb/lib/mongo_client.js:315:5)
at /Users/farooqkhan/Documents/mongoIDE/adminMongo/node_modules/mongodb/lib/mongo_client.js:234:11
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)

npm ERR! Darwin 16.1.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "start"
npm ERR! node v6.9.1
npm ERR! npm v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! admin-mongo@0.0.3 start: `node app.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the admin-mongo@0.0.3 start script 'node app.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the admin-mongo package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node app.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs admin-mongo
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls admin-mongo
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /Users/farooqkhan/Documents/mongoIDE/adminMongo/npm-debug.log


I dont understand whats wrong here. Everything used to work fine I dont know what happened suddenly. I even tried re-installing MongoDB but nothing helped.

Answer

It looks like the collection doesn't have a data, can you verify that your node-angular2 modules have user table and it has data?

You can do this by a third party tool like robomongo or through shell connect with mongo command.

meanwhile you can modify your code to do some error handling

var express = require('express');
var router = express.Router();
var User = require('../models/user');

router.get('/', function (req, res, next) {

    User.findOne({}, function(err, doc) {
        if (err) {
            return res.send('Error!');
        }
        if(doc){
           res.render('node', {email: doc.email});
        }else{
           res.render('node', {email: null});
        }
    });
});

router.post('/', function(req, res, next) {
    var email = req.body.email;
    var user = new User({
        firstName: 'Max',
        lastName: 'Schwarz',
        password: 'super-secret',
        email: email
    });
    user.save(function(err){
       if(err){
         console.log("couldn't save");
       }
       res.redirect('/');
    });
});
module.exports = router;

As you can see I have modified your post call and am calling redirect in the callback of save function, which means it will redirect only when user is saved.

when res.json or res.redirect is called without completing the previous operation, previous operations are cancelled inherently.