Home > Software design >  ERR_MODULE_NOT_FOUND: Cannot find Module Error
ERR_MODULE_NOT_FOUND: Cannot find Module Error

Time:06-21

Problem Summary

I am working on the backend of a MERN stack app that pulls restaurant data from a mongo collection. When I run nodemon server inside of the backend folder, I obtain the error ERR_MODULE_NOT_FOUND:

[nodemon] 2.0.16
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server index.js`
node:internal/errors:466
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '[redacted]/backend/dao/restaurants.DAO' imported from [redacted]/backend/api/restaurants.controller.js
    at new NodeError (node:internal/errors:377:5)
    at finalizeResolution (node:internal/modules/esm/resolve:405:11)
    at moduleResolve (node:internal/modules/esm/resolve:966:10)
    at defaultResolve (node:internal/modules/esm/resolve:1174:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:605:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:318:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)
    at link (node:internal/modules/esm/module_job:78:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Node.js v18.2.0
[nodemon] app crashed - waiting for file changes before starting...

Problem Details

My Folder Structure

My folder structure looks like this

restaurant.route.js

import express from "express";
import RestaurantsCtrl from "./restaurants.controller.js";


// create router instance
const router = express.Router();

// respond to GET requests with hello
router.route("/").get(RestaurantsCtrl.apiGetRestaurants);

export default router;

restaurants.controller.js

import RestaurantsDAO from "../dao/restaurants.DAO";

export default class RestaurantsCtrl {
    static async apiGetRestaurants(req, res, next) {
        // if there is a number of restaurants to show per page passed in the URL, conver it to an integer. Otherwise set it to 20
        const restaurantsPerPage = req.query.restaurantsPerPage ? parseInt(req.query.restaurantsPerPage, 10) : 20;
        // if there is a page number passed in the URL, conver it to an integer. Otherwise set it to 0
        const page = req.query.page ? parseInt(req.query.page, 10) : 0;

        let filters = {};
        // if we see filters passed in the URL, add it to the filters
        if (req.query.cuisin) {
            filters["cuisine"] = req.query.cuisine;
        }
        else if (req.query.zipcode) {
            filters["zipcode"] = req.query.zipcode;
        }
        else if (req.query.name) {
            filters["name"] = req.query.name;
        }

        // get the list of restaurants and a number of restaurants from the database
        const { restaurantsList, totalNumRestaurants } = await RestaurantsDAO.getRestaurants({
            filters,
            page,
            restaurantsPerPage,
        });
        
        // create a response object to send back to the client
        let response = {
            restaurants: restaurantsList,
            page: page,
            filters: filters,
            entries_per_page: restaurantsPerPage,
            total_results: totalNumRestaurants,
        }

        // send the response back to the client
        res.json(response);
    }
}


server.js

import express from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js";

// Create a new express application instance 
const app = express();
// apply middleware
app.use(cors());
// parse request body as JSON. Our server can accept JSON data in the body of a request
app.use(express.json());

// specify some routes. This is the path that will be used to access the API 
app.use("/api/v1/restaurants", restaurants);
// If someone goes to a path that doesn't exist, return a 404 error
app.use("*", (req, res) => res.status(404).json({error : "Not found"}));

// export the application instance for use in the rest of the application
export default app

index.js

import app from "./server.js"
import mongodb from "mongodb";
import dotenv from "dotenv";
import RestaurantsDAO from "./dao/restaurants.DAO.js";


// Load environment variables from .env file, where API keys and passwords are configured
dotenv.config();
// Get access to the mongo client
const MongoClient = mongodb.MongoClient;

// set port
const port = process.env.PORT || 8000; 

// Connect to the database
const a = MongoClient.connect(
    // The URL of the database to connect to
    process.env.RESTREVIEWS_DB_URI,
    {
        // The options to use when connecting to the database
        maxPoolSize: 50,
        wtimeoutMS: 2500,
        useNewUrlParser: true,
    }
    )
    // If the connection is not successful, throw an error
    .catch(err => {
        console.log(err.stack);
        process.exit(1);

    })
    // If the connection is successful, console log a message
    .then(async client => {
        // Get a reference to the database
        await RestaurantsDAO.injectDB(client);

        app.listen(port, () => {
            console.log(`Server listening on port ${port}`);
        });
    });

CodePudding user response:

I found the solution to this problem.

I needed to add .js at the end of restaurants.DAO in the line import RestaurantsDAO from "../dao/restaurants.DAO"; of the file restaurants.controller.js

  • Related