简体   繁体   中英

How to save mongodb findone value to a javascript variable to use it later on nodejs

I have spent tow day to solve this problem but got nothing. All the answers in stackoverflow didn't work for me.

here is my code

const userCredential = require("./db").db().collection("api");

now I want to retrieve a doc like API to save it on a variable

const api = userCredential.findOne({username:'admin'}, (err, doc)=> (doc.username))

and now I want to use the variable to anywhere in the file. But it returned undefined.

if I try this one

let api;
userCredential.findOne({username:'admin'}, (err, doc)=> (api = doc.api))

also return undefined because of nature of Asynchronous.

How can I save in to a variable?

Please try below code

function query(username) {
  console.log('query');
  Test.findOne({ username: username }, function (err, result) {
    console.log('findOne callback');
    if (err) {
      return console.error(err);
    } else {
      console.log(`result: ${result}`);
      return ${result};
    }
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM