I am using Nodemon and ESM module to use ES6 syntax on a Express + Mongoose project. I am getting this error when compiling:
SyntaxError: The requested module 'file:///.../models/User.js' does not provide an export named 'User'
My model file (models/User.js) looks like this:
import mongoose, { Schema } from 'mongoose';
const userSchema = new Schema({
name: String,
email: String,
password: String,
type: String,
createdOn: String,
updatedOn: String
});
const User = mongoose.model('user', userSchema);
module.exports = { User };
And then I import it:
import { User } from '../models/User';
import bcrypt from 'bcrypt';
export default {
Query: {
getUsers: async () => await User.find({}).exec()
},
Mutation: {
addUser: async (_, args) => {
try {
const user = args;
user.password = await hashPassword(args.password);
user.createdOn = Date.now();
user.updatedOn = Date.now();
let response = await User.create(user);
return response;
} catch(e) {
return e.message;
}
}
}
};
I was following this guide, but he uses ES5 syntax. Any suggestions are appreciated.
To solve the error "The requested module does not provide an export named 'default'", use the default keyword when exporting a value from a file and don't wrap the corresponding import in curly braces. You can only have a single default export per file.
Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export.
TypeScript supports export = to model the traditional CommonJS and AMD workflow. The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.
The export statement is used when creating JavaScript modules to export objects, functions, variables from the module so they can be used by other programs with the help of the import statements.
You are mixing ES6 modules (import, export
) with CommonJS (require/module.exports
). We are going to need to replace module.exports = { User };
with export const User = mongoose.model('user', userSchema);
in order to succesfully import it as an ES6 module in your other file. You can create a named export in your model file as follows:
import mongoose, { Schema } from 'mongoose';
const userSchema = new Schema({
name: String,
email: String,
password: String,
type: String,
createdOn: String,
updatedOn: String
});
export const User = mongoose.model('user', userSchema);
Which will then allow you to import like this:
import { User } from '../models/User';
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