Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS cannot find module error for file in another folder

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
like image 963
xtabbas Avatar asked Sep 14 '16 17:09

xtabbas


1 Answers

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
    });

});
like image 142
RootHacker Avatar answered Oct 04 '22 05:10

RootHacker