TypeError: User is not a constructor

前端 未结 5 1535
长情又很酷
长情又很酷 2020-12-21 16:40

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

相关标签:
5条回答
  • 2020-12-21 17:08

    Changing the lowercase user variable into uppercase (like below) strangely worked:

    const User = mongoose.model('users');

    I really thought this was just a best practice but eventually, seems to be mandatory.

    0 讨论(0)
  • 2020-12-21 17:25

    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)
    
    0 讨论(0)
  • 2020-12-21 17:27
    // models/user.js
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var UserSchema = new Schema({
        email: {
            type: String,
            unique: true,
            lowercase: true
    },
        password: String
    });
    
    var User = mongoose.model('User', UserSchema)
    module.exports =  { User } <-- capital 'U'
    
    0 讨论(0)
  • 2020-12-21 17:31

    I was also facing the same error but this worked for me.

    I did change my export file

    var User = mongoose.model('User',userSchema);
    module.exports = {User};
    

    To

    module.exports = mongoose.model('User', userSchema);
    
    0 讨论(0)
  • 2020-12-21 17:32

    Change this var user = new User(); for this var User = new User();

    0 讨论(0)
提交回复
热议问题