0

I am trying to read a from Mongo DB and assign a value to a variable . Does not work.

var collection = db.get('accesstoken');
  collection.find({},{},function(e,docs){
    console.log(docs);
    var global_token_var = docs.toArray()[0].access_token;
    console.log(" global token variable set to " + global_token_var);
  });

Output as below

[ { _id: 594aaa17f0db330e70bd6e89, access_token: '76c9b8a60b4f4402bdc7082b945d77899f1282d2', Expires_in: 86400000 } ] undefined (node:1104) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejec tion id: 1): TypeError: Cannot read property 'toArray' of undefined*

So console.log(doc) is returing the JSON object correctly. but variable remains undefined . I need the access_token in a variable . Where am I going wrong ?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
chittasec
  • 21
  • 5

1 Answers1

0

sorry i cant comment, but i think you need to require body parser, they have a json parser for incoming requests:

https://www.npmjs.com/package/body-parser

app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json 
app.use(bodyParser.json())

also question might be related to this: What does body-parser do with express in nodejs?

thats if your using express, if not then i would imagine you would have to parse in some way. i use express so i would recommended the package. hope im reading this correctly, best of luck

  • Um. No. The question has a simple error where the OP has misinterpreted the documentation. This answer has nothing to do with the question and the question is actually resolved if you actually read the comments. – Neil Lunn Jun 22 '17 at 01:07