0

I am making a user registration form witch insert a record to the mongodb. I am using there fore:

  • MongoDB version v2.6.11
  • NodeJS version v0.10.25
  • Express version 4.13.1

All works fine except when a use a constructor var newUser = new User({...}); it returns the error Object is not a function

The rest works fine. I get the logging before it returns the error but i don't know how to fix this.

users.js

var express = require('express');
var router = express.Router();

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

/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});

router.get('/Registreren', function(req, res, next) {
res.render('Registration', { title: 'Registreren' });
});

router.get('/Aanmelden', function(req, res, next) {
res.render('Aanmelden', { title: 'Aanmelden' });
});

router.post('/Registreren', function(req, res, next){
// Get form value
console.log('Bericht in behandeling ...')
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password_confirm = req.body.password_confirm;

console.log('username: ' + username);
console.log('email: ' + email);
console.log('password: ' + password);
console.log('password_confirm: ' + password_confirm);
console.log('FIRST TEST: ' + JSON.stringify(req.file));
console.log('SECOND TEST: ' + req.file.profileimage);
console.log('THIRD TEST: ' + req.file.originalname);

// Check for image field
if (req.file || req.file.profileImage){
    console.log('Uploading file....');

    //File Info 
    var profileImageOrginalName     = req.file.originalname;
    var profileImageName            = req.file.name;
    var profileImageMimetype        = req.file.mimetype;
    var profileImagePath            = req.file.path;
    var profileImageExt             = req.file.extension;
    var profileImageSize            = req.file.size;
} else{
     console.log('profileImageFile not found....');
    // Set default image
    var profileImageName = 'noimage.png';
}

// Form validation
    req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
    req.checkBody('email','email is verplicht').notEmpty();
    req.checkBody('email','email is niet geldig').isEmail();
    req.checkBody('username','Gebruikersnaam is verplicht').notEmpty();
    req.checkBody('password','Wachtwoord is verplicht').notEmpty();
    req.checkBody('password_confirm','Wachtwoorden zijn niet `gelijk').equals(req.body.password);`

// Error handling

var errors = req.validationErrors();
console.log(errors);
if(errors){
    console.log('Error handling....');
    res.render('Registration',{
        errors: errors,
        email: email,
        username: username,
        password: password,
        password_confirm: password_confirm
    });
} else {
    console.log('Make new User ....');
    console.log('email: ' + email);
    console.log('username: ' + username);
    console.log('password: ' + password);
    console.log('profileImageName: ' + profileImageOrginalName);

    var newUser = new User({
        email: email,
        username: username,
        password: password,
        profileimage: profileImageOrginalName
    });

    console.log('---------------- START TEST----------------------------');
    console.log('FIRST TEST: ' + JSON.stringify(newUser));
    console.log('SECOND TEST: ' + newUser);

    // Create User
    User.createUser(newUser, function(err,user){
        if(err) throw err;

    });

    // Succes message
    req.flash('succes','Je bent succesvol aangemedld');
    res.location('/');
    res.redirect('/');    
    } 
    });

    module.exports = router;

APP.JS

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 session = require('express-session');
var methodOverride = require('method-override');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;


var routes = require('./routes/index');
var users = require('./routes/users');



var app = express();

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

// Handle file Uploads
app.use(multer({dest:'./uploads/'}).single('profileimage'));

// 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 }));

//Handle Express Sessions
app.use(session({
        secret: 'secret',
        saveUninitialized: true,
        resave: true
        }));


//Passport
app.use(passport.initialize());
app.use(passport.session());      

//Vallidator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));



app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// Flash
app.use(flash());

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

user.js

console.log('Mongoose Start....');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Users');
var db = mongoose.connection;

    db.once('open', function (callback) {
    //user Schema
    var UserSchema = mongoose.Schema({
       username: {
           type: String,
           index: true
       },
        password: {
            type: String,
        },
        email: {
           type: String,
       },
        profileimage: {
           type: String,
       }
    });
    console.log('Create record!');
    var User = module.exports = mongoose.model('User',UserSchema);



    module.exports.createUser = function(newUser, callback){
        newUser.save(callback);

        console.log('USER: ' +  newUser)    
    };
});

What i have tried an read

I have read the following post:

I have tried to build more logging as you can see in the scripts so i can pin point where the problem come from. But i don know how to fix this. I hope you can help me.

2
  • You're exporting the Mongoose model. Is that a function? Commented Oct 1, 2015 at 13:17
  • 3
    You export the user model, but then set module.exports.createUser to a function. That doesn't look right and is likely breaking things. You'd want to create createUser as a static method in the Mongoose schema instead. Commented Oct 1, 2015 at 13:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.