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 data back from mongodb.
The problem I'm running into is explained by the code below
function get_data()
{
var mongo = require('mongodb'),Server = mongo.Server,Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('test', server);
db.collection('test_collection', function(err, collection) {
collection.find().toArray(function(err, items) {
var data = items;
});
});
console.log(data);
console.log("in get");
return data;
}
How do I return the items Array I pulled from mongo db from this function.
I want to know how scoping works in javascript and how do I put the items in a variable and return them from the get_data function.
After the answer
I fixed the code. It now works and looks like this.
function get_data(callback) {
var mongo = require('mongodb'),Server = mongo.Server,Db = mongo.Db;
var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('test', server);
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);
});
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);
});