Reputation: 647
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
Upvotes: 7
Views: 20983
Reputation: 1107
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
});
});
Upvotes: 4
Reputation: 101
You are exporting a variable myModel from schema.js and importing just schema in index.js
So, try to reference the .find function using myModel.myModel.find()
My guess is that the myModel variable is behind your existing myModel variable in index.js
Upvotes: 0