Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

module.export function not returning results

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
like image 529
user1460015 Avatar asked Sep 18 '13 23:09

user1460015


People also ask

CAN module exports be a function?

module. Exports is the object that is returned to the require() call. By module. exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.

What's the difference between module exports and exports?

When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way.

Does module exports work in browser?

exports . If module is not declared, an exception is thrown. This file can be included in both the browser and node.

What does module exports do in JavaScript?

Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.


1 Answers

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);
});
like image 78
hexacyanide Avatar answered Sep 19 '22 10:09

hexacyanide