javascriptexpressmongoose

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


Solution

  • 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)