0

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

TzelonM
  • 41
  • 3
  • 1
    Maybe you should first read the documentation and a tutorial of node.js. I'm afraid you're far away from the right solution, but you should understand it. Correcting your example doesn't make sense. – hgoebl Dec 21 '13 at 21:23
  • Forget the node.js part. When I connect to mongodb and retrieve a collection. I can use the find function to retrieve data right? Now, I don't understand how to use this data cause when I try to use it (Like the above example) ddocs = docs when docs is the data. I can undefined on the ddcos – TzelonM Dec 21 '13 at 21:58
  • 1
    No, node.js has a very particular programming model and node-mongodb-native is strictly aligned to it. If you don't understand node.js, forget about accessing MongoDB from JavaScript. Then you have to use another language. – hgoebl Dec 21 '13 at 22:09
  • OK, back to the node.js documentation. Thank you. – TzelonM Dec 21 '13 at 22:10
  • 1
    Look for details about dealing with async response. The essence of this question is asked frequently in the NodeJs tags of StackOverflow, as well as MongoDb. – WiredPrairie Dec 21 '13 at 22:19
  • Thank you, for given me a direction. I understand what I did wrong :) – TzelonM Dec 21 '13 at 23:01

1 Answers1

0

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.

EmptyArsenal
  • 7,314
  • 4
  • 33
  • 56