user1460015
user1460015

Reputation: 2003

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

Upvotes: 7

Views: 12549

Answers (2)

Rajib
Rajib

Reputation: 592

i solve similar problem in different way. I am not sure whether it is right way.

in main node js I am using a model named product. I am passing product and res to misc.js. Following is part of my server.js file

var misc = require('./misc');
app.get('/groupbyCategory', function(req,res,next)
   {
     var res2; 
     misc.addX(product,res);
    })

IN misc.js doing group by function and will return that value to straight way to angular controller. it is not necessary to return the result to server.js and from server.js to return angular controller. So i feel waiting and other call back seems unnecessary. Inside misc.js i keep following code.

exports.addX = function(product,res) {
 product.aggregate([

 { $group: {
 _id: {category: "$category"},
     count: { $sum: 1 }
        }}    
     ], function (err, result) {
     if (err) {
     console.log(err);
     return err; 
       }
       else
       {  
       //return result;

        console.log(result);
        res.send(result);
        }
    });


};

Upvotes: 0

hexacyanide
hexacyanide

Reputation: 91609

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

Upvotes: 22

Related Questions