Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript User Authentication With Express and Mongo User Registration Adding Data to the Database

User.create Method Not Working

Hi guys,

I just can't seem to get past this point at all. Whenever I try to create a new user and add it to the database my site hangs for ages waiting for a response from the server before getting an error of "localhost didn't send any data. ERR_EMPTY_RESPONSE".

I've been over the last three videos a few times and checked that my code is the same as Dave's and it all looks good.

I've also been back over my code step by step to see where it is falling down and it appears to be in the User.create() method once all input has been verified and errors checked.

I've tried using console.log(UserData) to see what is happening and all the information from my form is being captured so I really don't know where I am going wrong.

Any help would be greatly appreciated.

My two files look like this:-

./models/user.js

var mongoose = require('mongoose');
var UserSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true
  },
  name: {
    type: String,
    required: true,
    trim: true
  },
  favoriteBook: {
    type: String,
    required: true,
    trim: true
  },
  password: {
    type: String,
    required: true,
  }
});

var User = mongoose.model('User', UserSchema);
module.exports = User;

./routes/index.js

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

// GET /register
router.get('/register', function(req, res, next) {
  return res.render('register', { title: 'Sign Up'});
});

// POST /register
router.post('/register', function(req, res, next) {
  if (req.body.email &&
    req.body.name &&
    req.body.favoriteBook &&
    req.body.password &&
    req.body.confirmPassword) {
      // Confirm that user typed same password twice
      if (req.body.password !== req.body.confirmPassword) {
        var err = new Error('Passwords do not match.');
        err.status = 400;
        return next(err);
      }

      // Create object with form input
      var userData = {
        email: req.body.email,
        name: req.body.name,
        favoriteBook: req.body.favoriteBook,
        password: req.body.password
      };

      // Use schema's 'create' method to insert document into Mongo
      User.create(userData, function (error, user) {
        if (error) {
          return next(error);
        } else {
          return res.redirect('/profile');
        }
      });

    } else {
      var err = new Error('All fields required.');
      err.status = 400;
      return next(err);
    }
});

// GET /
router.get('/', function(req, res, next) {
  return res.render('index', { title: 'Home' });
});

// GET /about
router.get('/about', function(req, res, next) {
  return res.render('about', { title: 'About' });
});

// GET /contact
router.get('/contact', function(req, res, next) {
  return res.render('contact', { title: 'Contact' });
});

module.exports = router;

2 Answers

I figured it out.

My database connection was wrong. I had changed the code to mongoose.createConnection() instead of mongoose.connect() as per the video.

Which raises another question for me though:-

The reason I did that was when I ran my app originally with the correct method, nodemon threw a deprecation warning and suggested I use openUri() or createConnection() if using connect().

Why is the warning being thrown? And is it something I need to worry about?

Cheers Don :-)

Seth Kroger
Seth Kroger
56,413 Points

When you successfully create a user you redirect to /profile but the route for it isn't in the routes file.

Thanks Seth, that route comes in the next video. At this point we're just looking to redirect to a "file not found" error page but that wasn't working either.