Home Ask Login Register

Developers Planet

Your answer is one click away!

MM1 February 2016

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.

Answers


Festo February 2016

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


Eric Coutu February 2016

As mentioned in another answer, this code is asynchronous, you can't simply return the value you want down the chain of callbacks (nested functions). You need to expose some interface that lets you signal the calling code once you have the value desired (hence, calling them back, or callback).

There is a callback example provided in another answer, but there is an alternative option definitely worth exploring: promises.

Instead of a callback function you call with the desired results, the module returns a promise that can enter two states, fulfilled or rejected. The calling code waits for the promise to enter one of these two states, the appropriate function being called when it does. The module triggers the state change by resolveing or rejecting. Anyways, here is an example using promises:

Db1.js:

// db1.js
var MongoClient = require('mongodb').MongoClient;
/*
node.js has native support for promises in recent versions. 
If you are using an older version there are several libraries available: 
bluebird, rsvp, Q. I'll use rsvp here as I'm familiar with it.
*/
var Promise = require('rsvp').Promise;

module.exports = {
  FindinCol1: function() {
    return new Promise(function(resolve, reject) {
      MongoClient.connect('mongodb://localhost:27017/db1', function(err, db) {
        if (err) {
          reject(err);  
        } else {
          resolve(db);
        }        
      }
    }).then(function(db) {
      return new Promise(function(resolve, reject) {
        var collection = db.collection('col1');
        
        collection.find().toArray(function(err, items) {
          if (err) {
            reject(err);
      

Post Status

Asked in February 2016
Viewed 2,520 times
Voted 13
Answered 2 times

Search




Leave an answer


Quote of the day: live life

Devs Planet ®

2014-2016 www.devsplanet.com

Devs Planet © all rights reserved

Search