module.export function not returning results
11,634
The reason you're getting no results is that you're trying to return a function value synchronously from an asynchronous callback. Instead of providing a function value, the return statement will instead stop the function, as return;
would normally do. This is why you must use a callback for asynchronous operations:
module.exports = exports = function(library, callback) {
modCodes.findOne({name: library}, {modcode: 1}, function (err, mc) {
if (err) throw new Error(err);
var db = mongoose.createConnection('mongodb://localhost:27017/' + mc.modcode + '?safe=true');
var models = {
Books: db.model('books', require('./schemas/books'))
}
callback(models);
});
};
And this is how you would be able to use it:
var Models = require('../models');
Models('myLibrary', function(models) {
console.log(models);
});
Author by
user1460015
Updated on June 19, 2022Comments
-
user1460015 almost 2 years
I'm having some problems returning results from a module function.
Below are two files that I'm working with.When I call the exported function it returns nothings.
Any suggestions/fixes as to why? Does it have to do with callbacks?models/index.js
module.exports = exports = function(library) { modCodes.findOne({name: library}, {modcode:1}, function(err, mc) { if (err) throw new Error(err); var db = mongoose.createConnection('mongodb://localhost:27017/' + mc.modcode + '?safe=true'); var models = { Books: db.model('books', require('./schemas/books')) } return models; }); };
books.js
var Models = require('../models'); console.log(Models("myLibrary")); //return nothing