[英]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.