Patrik Šimunič Patrik Šimunič - 6 months ago 33
Javascript Question

MongoDB + node.js - SQL Select equivalent

I'm pretty new to node.js and mongodb. I need a function, that will return an array with results from database. When I query 'SELECT * FROM table' in php, it returns array or array of objects. But with node and mongo I have to use lot of code, which seems so unnecessary to me. So I wrote this function:

select: function (table, terms) {
var rows = [];
var find = function (error, db) {
var collection = db.collection(table);
var docs = collection.find(terms);
docs.each(function (error, doc) {
rows.push(doc);
});
};
client.connect(url, find);
return rows;
}


It takes table name [string] and terms [js object] as arguments. And I want to this function return an array like this: [ { doc1 }, { doc2 }, { doc3 }, ...].
When I log variable doc, in each function, it's alright - valid javascript object. But when I log variable rows after pushing all docs, it's empty - []. Also the result of function select() is empty array - [].

Please, is there someone who has an idea about what could be a problem or who uses some similar method to fetch data from MongoDB? Thank you

Answer

The connect function is asynchronous, and finishes after your return statement. Put your return statement within the callback function, just after the closing bracket of docs.each(.....); This way you're sure your return statement will be executed after your array has been filled.

Edit for completeness: a return statement doesn't work of course, because it returns from the function in find. Work with a callback function.

Like this:

select: function (table, terms, cb) {
    var rows = [];
    var find = function (error, db) {
        var collection = db.collection(table);
        var docs = collection.find(terms);
        docs.each(function (error, doc) {
            rows.push(doc);
        });
        cb(error, rows);
    };
    client.connect(url, find);
}

Edit: Above example (cb function instead of return)

Comments