mongodb native how to work with query

89 Views Asked by At

I'm trying to retrieve data from my mongolab DB using Node-mongodb-native

var findAll = function () {
   var ddocs;   
   collection.find({}).each(function (arr, docs) {
    ddocs = docs;
   });
   console.log(ddocs);
};

But it seems that when I log ddocs, it will give me undefined, but if I log docs it will show me the data.

Please help How should I use this function ?

Thanks Tzelon Machluf

1

There are 1 best solutions below

3
On

You're basically trying to create a function that will return all of the documents in a collection? If so, the below should do work. However, I agree with @hgoebl and that you should work on your understanding of node as this is not likely the best way to accomplish what you're trying to do.

var ddocs;

var findAll = collection.find().toArray( function(err, docs) {
    if(err)
        throw err;
    console.log('Collection returned');
    return ddocs = docs;
});

setTimeout( function(err) {
    if(err) throw err;
    console.log(ddocs);
    db.close();
}, 1000);

One thing in particular to note: collection.find is asynchronous, so the problem in your code (why it says ddocs is undefined) is that you're logging ddocs before the collection.find ever finished; thus, it's initialized, but no assigned any values. The Node convention is to nest callbacks so that everything happens in the right order and when it's ready.