Node JS cannot find module error for file in another folder

16,297

Resolve path to schema.js correctly

Assuming your project structure like this

Project
 |
 +-- routers
 |  |  
 |  +-- index.js    
 +-- models
 |  |  
 |  +-- schema.js


//in index.js 
var schemas = require('../models/schema');

To solve second error i.e myModel.find not a function use, module.exports instead of using module.export

module.exports = myModel;

Resolution to your 3rd Problem

// controllers/findallusers.js --> (keep name simple  i.e userController.js)
var myModel = require('../models/schema');

module.exports =  {

    /**
     * Get All Users
     */
    list: function(req, res) {
       myModel.find({},function(err, users){
          if(err) {
              return res.status(500).json({message: 'Error getting Users.'});
          }
         return res.json(users);
      });
    },
   /**
    * Keep Adding more functions as you want
   */

   create: function(req,res){
       //functionality to create user
   },

   delete: function(req,res){
      // functionality to delete user
   },

   someDummyName: function(callback) {
       myModel.find({},function(err, users){
          if(err) {
            return callback(err)
          }
         return callback(null,users);
      });
    }       

}

// Solution to your question https://stackoverflow.com/questions/39504219/how-to-use-use-callbacks-or-promises-to-return-a-object-from-an-asynchronous-fun

//index.js call this new method i.e someDummyName as  
router.get('/allusers', function(req, res){       

    userController.someDummyName(function(err,result){
      if(err) {
        //return err
      }
      //process result as per your need
    });

});
Share:
16,297
xtabbas
Author by

xtabbas

I'm into coding apps, designing user experiences and writing about ideas, inspiration and tech on the internet. If you want to work with me DM.

Updated on June 19, 2022

Comments

  • xtabbas
    xtabbas almost 2 years

    If i have schema.js in the same folder as index.js doing something like

    var schemas = require('./schema');

    works fine, but if i put the schema.js in another folder and write

    var schemas = require('./folder/schema');

    i get an error Cannot find module whats happening?

    Edit1 : I got rid of the error by using ..folder/schema instead of single. and the server runs but it still doesn't work properly as I cant use the mongoosedb object returned through module.export from ../model/schema in the index.js file. It says myModel.find is not a function. Whats going on??

    controllers/findallusers.js

    var myModel = require('../models/schema');
    
    var alluser;
    
    myModel.find({}, function(err, foundData){   
      if(err){
        console.log(err);
        res.status(500).send();
      }
      else{
            alluser = foundData;
          }
    
        console.log(alluser); <-- this log is defined
    });
    
        console.log(alluser); <-- this log is undefined
    
        module.exports = alluser; <-- cant export anything
    
  • xtabbas
    xtabbas over 7 years
    created a package.json file in /models/ folder with what you mentioned. still getting error Cannot find module './models/schema'
  • xtabbas
    xtabbas over 7 years
    Is this real life? using two dots before /model/schema just solved the issue -_-
  • xtabbas
    xtabbas over 7 years
    Actually it still doesn't work properly.. I cant use the mongoosedb object returned through module.export from ../model/schema in the index.js file. It says myModel.find is not a function. Whats going on??
  • xtabbas
    xtabbas over 7 years
    Using ..models/schema solved the server issue of module not found error, but now i cant use the database model object which is exported from schema.js in the index.js. whats going on... can you help?
  • xtabbas
    xtabbas over 7 years
    I have added the code, also using the model/schema code directly in the index.js works just fine
  • lplatz
    lplatz over 7 years
    Theres my attempt, havnt used mongoose before but in my initial research of it, i think that my be it
  • RootHacker
    RootHacker over 7 years
    check my edited answer, and if its solved all your issues accept the answer.
  • xtabbas
    xtabbas over 7 years
    Please read my last edit, i used the .exports a while ago (that was silly of me) and im stuck in a new problem. can you tell me why alluser is getting undefined right after the call back function?
  • RootHacker
    RootHacker over 7 years
    check this link stackoverflow.com/a/39481543/4066767, I have explained it over there
  • xtabbas
    xtabbas over 7 years
    So can i use the module.exports inside the async function? doing that also returning null value { } in the log. How can use that db result?
  • RootHacker
    RootHacker over 7 years
    check resolution to your 3rd problem I'v edited the answer again..!
  • xtabbas
    xtabbas over 7 years
    Im getting error over here : list: function(req, res){ SyntaxError: Unexpected token ( whats wrong?
  • RootHacker
    RootHacker over 7 years
    check edited answer now, module.exports need to be object.
  • xtabbas
    xtabbas over 7 years
    Okay, i used the data by going ` console.log(allUser.list());` and its working. for now :)
  • xtabbas
    xtabbas over 7 years
    Turn out i was using console.log(users) in list : function, please tell me how to send the objects as json because its saying Cannot read property 'json' of undefined when i use return res.json(users);
  • RootHacker
    RootHacker over 7 years
    you need to call list() by passing req,res i.e allUser.list(req,res)
  • RootHacker
    RootHacker over 7 years
    var userController = require('../controllers/findallusers'); app.get('/allusers', function (req, res) { userController.list(req,res) })
  • xtabbas
    xtabbas over 7 years
    okay i get what is happening, but doesn't this mean that we are using the controller.js file for no reason?
  • RootHacker
    RootHacker over 7 years
    then pass only callback function to the list and change your list function accordingly. it would be better if you move this to a new question so that scope of this question will remain unchanged.
  • xtabbas
    xtabbas over 7 years
    stackoverflow.com/questions/39504219/… I have moved this to another question as you suggested.
  • xtabbas
    xtabbas over 7 years
    Also what do you mean by passing only the callback function, can you quickly explain it here ?
  • RootHacker
    RootHacker over 7 years
    sure. I'm adding a new method to the same answer which will accept callback
  • RootHacker
    RootHacker over 7 years
    check now and to understand callback check this link stackoverflow.com/questions/37216699/… .
  • xtabbas
    xtabbas over 7 years
    I think i have alot to learn about the asynchronicity of javascript but right now im running late for my class lol thanks again for your answers