I'm using MongoDB, and have a connection and a client that work. When you run the following code, you can console.log() the result and see the proper output:
connect.then(async () => {
const dbo = client.db(prod == 1 ? "prodData" : "test");
let data = await dbo.collection("practitioners").findOne({"_id" : "Oq1tOesempf3jjLfrVrWaVtaROI3"}, function(err, result) {
if (err) throw err;
console.log(result); // works!!!
return result;
});
});
However, I'm trying to get the result outside of the function but I can't figure out the await/async part of this or how to do it as a promise. I've been fumbling around with this for a long time to help would be greatly appreciated:
const find = async (connect, client, prod = 0) => {
// this works
// let data2 = await axios.get('https://reqres.in/api/users?page=2');
// console.log(data2);
let data = await connect.then(async () => {
const dbo = client.db(prod == 1 ? "prodData" : "test");
await dbo.collection("practitioners").findOne({"_id" : "Oq1tOesempf3jjLfrVrWaVtaROI3"}, function(err, result) {
if (err) throw err;
return result;
});
});
console.log(data); // undefined should be value :(
return data;
}
Even something like this might help if you can get the data outside of the response:
connect.then(() => {
const dbo = client.db(prod == 1 ? "prodData" : "test");
let data = await dbo.collection("practitioners").findOne({"_id" : "Oq1tOesempf3jjLfrVrWaVtaROI3"}, function(err, result) {
if (err) throw err;
return result;
});
console.log(data); // undefined should be value :(
return data;
});
If someone can help me and guide me a bit more about explain exactly which parts of these functions are async and values are await, I would be very thankful. Also if you don't mind writing it as a promise with resolve, that might help me understand a bit more.
async/await), do not pass a callback.