Putting MongoDB queries, inserts and removes in module.exports or exports

310 views Asked by At

Is there a way to put MongoJS/Mongoose queries, inserts and removes in module.exports while getting an confirmation object back?

server.js

var mongoq = require('./models/mongoq.js');
var result = mongoq.connectToServer();
console.log(result);

mongoq.js

var mongojs = require('mongojs');
db = mongojs('config', ['questions']);
module.exports = {
   //var answer;
   connectToServer: function(){
      db.questions.find(function (err, docs) {
         return docs;
      }
   //return answer;
};

The result variable returns undefined, and if I put the return outside of a query, it wants to send it before doing the query.
Is there a way that I can force the module.exports to wait for the query before returning it?
Thank you

1

There are 1 answers

1
Michael Troger On BEST ANSWER

You can achieve this by my making use of a callback. I.e. you call the module from the other file with a function as parameter, this function has the result variable as parameter. This function will be executed when the query has completed.

server.js

var mongoq = require('./models/mongoq.js');
mongoq.connectToServer(function(result) {
   console.log(result);
});

mongoq.js

var mongojs = require('mongojs');
db = mongojs('config', ['questions']);
module.exports = {
   connectToServer: function(callback) {
      db.questions.find(function (err, docs) {
         callback(docs);
      });
   }
};