Using ES6 Imports & Exports I feel like I should be able to declare the import as
import mongoose, { Schema, Document } from 'mongoose';
but I get the error Module '"mongoose"' has no default export.
The below does work but it clearly isn't the right way to go about this import. The export default id like to remove too.
import * as mongoose from 'mongoose';
import { Schema, Document } from 'mongoose';
export interface IUser extends Document {
email: string;
password: string;
}
const UserSchema: Schema = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
export default mongoose.model<IUser>('User', UserSchema);
And then im using it with
import UserModel, { IUser } from '../models/example'
import * as bcrypt from 'bcrypt';
class User {
static register = async (req: Request, res: Response) => {
const email = req.body.email;
const password = req.body.password;
const alreadyRegistered = await UserModel.findOne({email}).exec();
if (!alreadyRegistered) {
const hashedPassword = await bcrypt.hash(password,10);
if (!hashedPassword) {
res.status(500).send({ message: "Failed to encrypt your password" });
} else {
const user = new UserModel(<IUser>{email:email, password:hashedPassword});
const saved = await user.save();
if (!saved) {
res.status(500).send({ message: "Failed to register you" });
} else {
res.status(200).send({ message: "You are now registered" });
}
}
} else {
res.status(400).send({ message: "You have already registered" });
}
};
}
export {User}
Export Default is used to export only one value from a file which can be a class, function, or object. The default export can be imported with any name.
To solve the error "The requested module does not provide an export named 'default'", be consistent with your ES6 imports and exports. If a value is exported as a default export, it has to be imported as a default import and if it's exported as a named export, it has to be imported as a named import.
The "Module has no default export" error occurs when we try to import as default from a module that doesn't have a default export. To solve the error make sure the module has a named export and wrap the import in curly braces, e.g. import {myFunction} from './myModule' .
The error "The requested module does not provide an export named" occurs when mixing up default and named ES6 module imports and exports. To solve the error make sure to import default exports without using curly braces and import named exports with curly braces.
I came across this issue and fixed it by adding the following to tsconfig.json
"esModuleInterop": true
Then I could import as normal
import mongoose from 'mongoose'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With