Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: User is not a constructor

I am trying to save a user to mongodb database using post request as follow, but I got the error TypeError: User is not a function. It's a pretty simple set up of the code but i can't figure out anything wrong with it.

I am using:
mongoose 4.8.6
express 4.15.2
node 6.6

// models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    email: {
        type: String,
        unique: true,
        lowercase: true
    },
    password: String
});

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

app.post('/create-user', function(req, res, next) {
    var user = new User(); // TypeError: User is not a constructor
    user.email = req.body.email;
    user.password = req.body.password;

    user.save(function(err) {
        if (err) return next(err);
        res.json('Successfully register a new user');
    });
});

enter image description here

like image 484
eulercode Avatar asked Jan 24 '26 11:01

eulercode


2 Answers

You need to create model from your UserSchema and then export it, then you can create new User objects.

// models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
    email: {
        type: String,
        unique: true,
        lowercase: true
    },
    password: String
});

module.exports =  mongoose.model('User', UserSchema)
like image 158
Nenad Vracar Avatar answered Jan 27 '26 00:01

Nenad Vracar


You got that error because you exported the modules wrongly,
In my case in the models/user I had written module.export leaving out the s at the end
When you run the code it then gives you that error
I would advice checking on your module.exports = mongoose.model('User', UserSchema) spellings

like image 25
Indeche Ojukwu Avatar answered Jan 26 '26 23:01

Indeche Ojukwu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!