TypeError:使用构造函数

时间:2015-10-01 13:11:08

标签: node.js mongodb express mongoose

我正在制作用户注册表格,以便将记录插入mongodb。我在那里使用:

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

一切正常,除非使用构造函数 var newUser = new User({...}); 它返回错误对象不是函数

其余的工作正常。我在返回错误之前得到了日志,但我不知道如何解决这个问题。

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

我尝试过阅读

我已阅读以下帖子:

我已尝试构建更多日志记录,您可以在脚本中看到,以便我可以确定问题的来源。但我不知道如何解决这个问题。我希望你能帮助我。

0 个答案:

没有答案