0

I have a working code that looks like this:

var test = {
      'tst' : function () {
          var collection = db.collection('subscriptions');
          collection.find().toArray(function(err, docs) {
            console.log(docs);
            db.close();
          });
      }
    }

Is there a way to pass the value of "docs" to a variable? I tried accessing the value of docs using the code below:

console.log(test.tst().collection().docs);

but not working, please help. Thank you

Website Is Fun
  • 290
  • 6
  • 20
  • `test.tst()` doesn't `return` anything that you could invoke a `.collection` method on. – Bergi Jan 18 '16 at 06:02
  • @Bergi - I tried adding return value to to collection and docs but still the return value is undefined. Where do you suggest I return the value? – Website Is Fun Jan 18 '16 at 06:11
  • Your code has two serious issues. 1) Method chaining does not work without returning an object. You seem to be confused at the difference between local variables and object properties. 2) your database access is asynchronous, you [cannot `return` a result value](http://stackoverflow.com/q/14220321/1048572) at all. See also the question linked by thefourtheye. – Bergi Jan 18 '16 at 06:16
  • Does this mean it is a dead end? I am using this node package: https://github.com/mongodb/node-mongodb-native is there a way to assign or pass the collection data to a variable or how to return the data so I can use the return value? – Website Is Fun Jan 18 '16 at 06:55
  • Yeah, more like a dead end. Read all the answers on the canonical questions we linked. Promises do allow you to use return values, but they're not the results themselves, they're just a proxy for the actual (asynchronous) data. – Bergi Jan 18 '16 at 06:58
  • I got it to work using `Promise(function() { }); ` :) – Website Is Fun Jan 18 '16 at 07:30

0 Answers0