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.
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.
Share Improve this question edited Apr 10, 2019 at 13:45 Maramal asked Apr 10, 2019 at 13:37 MaramalMaramal 3,4669 gold badges59 silver badges100 bronze badges1 Answer
Reset to default 17You 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';