eersteam eersteam - 1 month ago 5x
Javascript Question

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??


var myModel = require('../models/schema');

var alluser;

myModel.find({}, function(err, foundData){
alluser = foundData;

console.log(alluser); <-- this log is defined

console.log(alluser); <-- this log is undefined

module.exports = alluser; <-- cant export anything


Resolve path to schema.js correctly

Assuming your project structure like this

 +-- 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;