Reputation: 1529
I'm trying to implement registration in Express using passport.js and when I submit the form, on the server console I got:
POST /user/register 500 62.273 ms - 2008
TypeError: User is not a constructor
at /mean-auth/server/routes/api.js:8:17
Here is the api.js file with error:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user.js');
router.post('/register', function(req, res) {
User.register(new User({ username: req.body.username }),
req.body.password, function(err, account) {
if (err) {
return res.status(500).json({
err: err
});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({
status: 'Registration successful!'
});
});
});
});
module.exports = router;
User model (user.js
) looks like:
// user model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var bcrypt = require('bcrypt');
var userSchema = mongoose.Schema({
username: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
var User = mongoose.model('User', userSchema);
module.exports = {
User: User
};
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) throw err;
callback(null, isMatch);
});
}
and I also tried with createUser
method and newUser
object:
var User = require('../models/user.js');
router.post('/register', function(req, res) {
var username = req.body.username;
var password = req.body.password;
var newUser = new User({
username: username,
password: password
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
passport.authenticate('local')(req, res, function () {
return res.status(200).json({
status: 'Registration successful!'
});
});
});
but the same error appears. Is there something wrong with the definition of the User?
Upvotes: 0
Views: 653
Reputation: 1253
It seems that you are exporting an object with the User inside it.
module.exports = {
User: User
};
When importing that file, try to do it like this:
var User = require('../models/user.js').User;
Upvotes: 3
Reputation: 5425
You don't need the .js
extension in the require statement.
var User = require('../models/user');
Upvotes: 0