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
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.
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)
// 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'
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);
Change this var user = new User();
for this var User = new User();