In my nodejs, I have a small mongoose module which exports the model (User). When I require the module without using destructuring assignment and I create the new instance of the model using new operator, I get the error that the model is not a function. But if i use the destructuring assignment when I require the model, everything works fine. Not able to understand why.
User.js exports the model
const mongoose = require('mongoose');
exports.User = mongoose.model('User', {
email:{
type: String,
trim: true,
minlength: 1,
reuqired: true
}
});
Below code throws error if I dont use destructuring operator on line 2:
server.js
const mongoose = require('../DB/mongoose');
const User = require('../Models/User');
console.log(typeof(User));
let user = new User({
email: "sdfdsf"
});
server.js throws the below error:
let user = new User({
^
TypeError: User is not a constructor
at Object.<anonymous> (F:\javascript\nodePractice\ToDoApp\server\server.js:6:12)
at Module._compile (internal/modules/cjs/loader.js:678:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:719:10)
at startup (internal/bootstrap/node.js:228:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:576:3)
But If I use a
destructuringassignment online 2, it works all fine. server.js:
const mongoose = require('../DB/mongoose');
const {User} = require('../Models/User');
console.log(typeof(User));
let user = new User({
email: "sdfdsf"
});