简体   繁体   English

如何将 mongodb findone 值保存到 javascript 变量以便稍后在 nodejs 上使用

[英]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. stackoverflow 中的所有答案都对我不起作用。

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现在我想检索像 API 这样的文档以将其保存在变量中

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};
    }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将数组保存到文件中,然后再将其读入nodejs / JavaScript中的数组变量中? - How to save an array to file and later read it into an array variable in nodejs/JavaScript? Mongodb findOne() 没有返回值 nodejs - Mongodb findOne () not return value nodejs Mongodb,如何在 javascript map 中使用 findOne 方法 - Mongodb, how to use findOne method in javascript map jQuery ajax只想将1个值保存到变量中以使用以后的Javascript - Jquery ajax only want to save 1 value to a variable to use later Javascript nodejs如何使用findOne - nodejs how to use findOne 尝试将输出从RenderPartial保存到Javascript变量并在以后使用 - Trying to save output from RenderPartial to a Javascript variable and use it later 如何在每个循环中保存变量的值,以便以后可以使用这些值 - How do I save the value of a variable on each loop so I can use those values later 如何将文件输入内容存储在变量中供以后在 Nodejs 中使用? - How to store file input content in a variable for later use in Nodejs? 如何在javaScript中获取本地文件名并将其保存为变量以供以后使用? - How get local filename in javaScript and save it with variable for using it later on? 如何将MongoDB / Nodejs与Express结合使用以检索基于JavaScript的游戏的保存数据? - How to use MongoDB/Nodejs with Express to retrieve save data for a JavaScript-based game?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM