I'm impractical with node js. I have the following code:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("test").findOne(
{},
{ sort: { _id: -1 } },
(err, data) => {
console.log(data);
},
);
db.close();
});
I would like to use the variable "data" outside the scope of MongoClient.connect (). The problem should be that a callback function is used and is therefore executed asynchronously.
If I do something like this:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var x;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("test").findOne(
{},
{ sort: { _id: -1 } },
(err, data) => {
console.log(data);
x = data;
},
);
db.close();
});
console.log(x);
The result of x will be "undefined".
How can this problem be solved in general? How do you use variables outside of a certain scope in order to execute the code in a pseudo-synchronous manner?