I have a basic setup for a mern project with a UserModel in it.
import mongoose from "mongoose"
const UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String
})
const UserModel = mongoose.model('Users', UserSchema)
module.exports = UserModel
In my package.json I’ve added "type": "module",
I import the UserModel via import UserModel from './models/UserModel'
When I run nodemon I get this error:
node:internal/process/esm_loader:40
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/bian/Documents/WebDev/fullstack/demoapp/models/UserModel' imported from /home/bian/Documents/WebDev/fullstack/demoapp/App.js
Did you mean to import ../models/UserModel.js?
at new NodeError (node:internal/errors:406:5)
at finalizeResolution (node:internal/modules/esm/resolve:233:11)
at moduleResolve (node:internal/modules/esm/resolve:845:10)
at defaultResolve (node:internal/modules/esm/resolve:1043:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:383:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:352:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:228:38)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:85:39)
at link (node:internal/modules/esm/module_job:84:36) {
url: 'file:///home/bian/Documents/WebDev/fullstack/demoapp/models/UserModel',
code: 'ERR_MODULE_NOT_FOUND'
}
I’ve googled and tried to set the type to commonjs
and imported via require but nothing works
Can anyone explain what is going on and/or how to fix it?
2
Answers
Replace
import mongoose from "mongoose"
withconst mongoose = require("mongoose")
Did you try to replace :