I am new to JavaScript and currently learning mongoDB with node and mongoose. when I try to connect
with db, i got this error:
Did you mean to import ../config/dbConfig.js?
at finalizeResolution (node:internal/modules/esm/resolve:255:11)
at moduleResolve (node:internal/modules/esm/resolve:908:10)
at defaultResolve (node:internal/modules/esm/resolve:1121:11) at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:396:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:365:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:240:38)
at ModuleWrap. (node:internal/modules/esm/module_job:85:39)
at link (node:internal/modules/esm/module_job:84:36) {
code: ‘ERR_MODULE_NOT_FOUND’,
Please let me know where i did wrong and how to correct it in async & await?
dbconfig.js
import mongoose from 'mongoose';
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true, useUnifiedTopology: true
});
const connection = mongoose.connection;
connection.on('error', () => {
console.log('Error in connection to Database');
});
connection.on('connected', () => {
console.log('Connected to Database')
});
module.exports = mongoose;
index.js
import express from 'express';
const app = express();
require('dotenv').config();
import mongoose from './config/dbConfig';
const port = process.env.PORT || 3001;
app.listen(port, () => {
console.log(`Server running on localhost:${port}`)
});
2
Answers
You should create a object mongoose connect and return it in dbconfig.js. In index.js, you use this object to startup app and connect db. Example:
dbconfig.js
index.js
Your code is over engineered, connecting with mongoose is a fairly straightforward process. You seem to be using ES Module syntax so you can’t really mix
require()
andimport
together so I will provide an example using ES Module syntax. Please note that in future you need to provide a file extension to your modules that you import, i.e. you need to include the.js
file extension.