Skip to content Skip to sidebar Skip to footer

Node.js Mongodb Javascript Scoping Confusion

I'm developing a express.js application, without mongoose. What I'm trying to do is, to encapsulate calls to mongodb inside a function, pass the function some parameter and get the

Solution 1:

Since the items are retrieved from MongoDB asynchronously, the function get_data needs to accept a callback that will be used to return the results. I believe you'll also need to explicitly open the database connection.

function get_data(callback) {
    ...

    db.open(function(err, db) {
        if (err) return callback(err);

        db.collection('test_collection', function(err, collection) {
            if (err) return callback(err);
            collection.find().toArray(callback);
        });
    });
}

get_data(function(err, items) {
    // handle error
    console.log(items);
});

Post a Comment for "Node.js Mongodb Javascript Scoping Confusion"