Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js, Mongo find and return data

I’m new to node and mongo after 15 years of VB6 and MySql. I’m sure this is not what my final program will use but I need to get a basic understanding of how to call a function in another module and get results back.

I want a module to have a function to open a DB, find in a collection and return the results. I may want to add a couple more functions in that module for other collections too. For now I need it as simple as possible, I can add error handlers, etc later. I been on this for days trying different methods, module.exports={… around the function and with out it, .send, return all with no luck. I understand it’s async so the program may have passed the display point before the data is there.

Here’s what I’ve tried with Mongo running a database of db1 with a collection of col1.

Db1.js
var MongoClient = require('mongodb').MongoClient;
module.exports = {
    FindinCol1 : function funk1(req, res) {
    MongoClient.connect("mongodb://localhost:27017/db1", function (err,db) {
            if (err) {
                return console.dir(err);
            }
            var collection = db.collection('col1');
            collection.find().toArray(function (err, items) {
                    console.log(items);
                   // res.send(items);
                }
            );
        });
    }
};


app.js
a=require('./db1');
b=a.FindinCol1();
console.log(b);

Console.log(items) works when the 'FindinCol1' calls but not console.log(b)(returns 'undefined') so I'm not getting the return or I'm pasted it by the time is returns. I’ve read dozens of post and watched dozens of videos but I'm still stuck at this point. Any help would be greatly appreciated.

like image 817
MM1 Avatar asked Feb 06 '16 21:02

MM1


1 Answers

Yes, this is an async code and with a return you will get the MongoClient object or nothing, based on where you put.

You should use a callback parameter:

module.exports = {
  FindinCol1 : function funk1(callback) {
    MongoClient.connect("mongodb://localhost:27017/db1", function (err,db) {
      if (err) {
        return console.dir(err);
      }
      var collection = db.collection('col1');
      collection.find().toArray(function (err, items) {
        console.log(items);       
        return callback(items);     
      });
    });
  }
};

Pass a callback function to FindinCol1:

a.FindinCol1(function(items) {
  console.log(items);
});

I suggest you to check this article: https://docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks

like image 90
Gergo Avatar answered Sep 21 '22 10:09

Gergo