Mongodb find () returns undefined (node.js)

I have been playing around with mongodb in node.js. I made a basic collection with some data (I know it's checked there). When I try to run find () on a collection, it returns undefined. I don't know why this is so. Code below:

function get_accounts(){
    var MongoClient = mongodb.MongoClient;
    var url = "url";

    MongoClient.connect(url, function (err, db) {
      if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
      } else {
        //HURRAY!! We are connected. :)
        console.log('Connection established to database');
        var collection = db.collection('accounts');
        collection.find().toArray(function(err, docs) {
          console.log("Printing docs from Array")
          docs.forEach(function(doc) {
            console.log("Doc from Array ");
            console.dir(doc);
          });
        });
        console.log("mission complete");
        }
        db.close();
    }
  );
}

      

If you know why this is happening, I would love to hear your thoughts. thank you! A database is a database hosted in mongolab if that matters.

+3


source to share


2 answers


You get undefined because of the asynchronous nature of node.js, there is no logic anywhere in your code that tells the console.log statement to wait until it finishes before it prints out documents. You should understand the concept of callbacks in node.js. There are several issues here that you can fix. Many people new to node have a tendency to anger many anonymous functions, creating a dreaded "pyramid of doom" or callback hell . By choosing some features and naming them, you can make it much cleaner and easier to follow: find()



var MongoClient = require("mongodb").MongoClient

// move connecting to mongo logic into a function to avoid the "pyramid of doom"
function getConnection(cb) {  
    MongoClient.connect("your-mongo-url", function(err, db) {
        if (err) return cb(err);
        var accounts = db.collection("accounts");
        cb(null, accounts);
    })
}    
// list all of the documents by passing an empty selector.
// This returns a 'cursor' which allows you to walk through the documents
function readAll(collection, cb) {  
   collection.find({}, cb);
}

function printAccount(account) {  
    // make sure you found your account!
    if (!account) {
        console.log("Couldn't find the account you asked for!");
    }
    console.log("Account from Array "+ account);
}

// the each method allows you to walk through the result set, 
// notice the callback, as every time the callback
// is called, there is another chance of an error
function printAccounts(accounts, cb) {  
    accounts.each(function(err, account) {
        if (err) return cb(err);
        printAccount(account);
    });
}

function get_accounts(cb) {  
    getConnection(function(err, collection) {
        if (err) return cb(err);    
        // need to make sure to close the database, otherwise the process
        // won't stop
        function processAccounts(err, accounts) {
            if (err) return cb(err);
            // the callback to each is called for every result, 
            // once it returns a null, you know
            // the result set is done
            accounts.each(function(err, account) {
                if (err) return cb(err)  
                if (hero) {  
                    printAccount(account);
                } else {
                    collection.db.close();
                    cb();
                }
            })
        }
        readAll(collection, processAccounts);        
    })
}

// Call the get_accounts function
get_accounts(function(err) {  
     if (err) {
         console.log("had an error!", err);
         process.exit(1);
     }
});

      

+4


source


You may need to add an empty JSON object inside the search.

collection.find({})

      



The documentation can be found here .

0


source







All Articles