Node.js: Error importing module in app.js but file exists

51 Views Asked by At

I am encountering an error in my Node.js application where I'm trying to import a module in app.js from db.js, but it's failing with the error message:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'path/src/db' imported from /path/src/app.js

However, the db.js file exists in the specified directory.

app.js

import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import './db'

// Execute express
const app = express();

// Define PORT
const PORT = process.env.PORT || 8001;

//Middlewares
dotenv.config();
app.use(express.json());
app.use(cors());
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/', (req, res) => {
    res.send('Welcome buddy!');
});

app.listen(PORT, () => {
    console.log(`App running on http://localhost:${PORT}/`);
});

db.js

import mongoose from "mongoose";

// connect to the database
mongoose
    .connect(`${process.env.MONGO_URI}`, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        serverSelectionTimeoutMS: 5000, // Timeout after 5s
    })
    .then(() => {
        console.log('successfully connected to the db!');
    })
    .catch((err) => {
        console.log('failed to connect with db!', err);
    });

I've ensured that both files are in the correct directory. What could be causing this issue, and how can I resolve it?

if I move the database connection code directly into app.js, it works without any issues.

1

There are 1 best solutions below

1
Ravi Yadav On BEST ANSWER

You should export mongoose connection as a function from db.js and then use it in app.js

in db.js

import mongoose from "mongoose";

// connect to the database
const connectDb = async () => {
      mongoose
        .connect(`${process.env.MONGO_URI}`, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            serverSelectionTimeoutMS: 5000, // Timeout after 5s
        })
        .then(() => {
            console.log('successfully connected to the db!');
        })
        .catch((err) => {
            console.log('failed to connect with db!', err);
        });
}
     
module.exports = {connectDb};

And use it in app.js:

import { connectDb } from '.path-to-file/db';
connectDb();