0

I maked query function for my project. But result always is null, how i can debug this code?

const queryDB = async (collection,filter) =>  {
  let result = null
  await MongoClient.connect(url, function(err, getDb) {
    if (err) throw err;
    const db = getDb.db("global"); 
    db.collection(collection).findOne(filter, function(err, result) {
      if (err) throw err;
      result = result
    })
  })
  return result
}
Wraithdev3
  • 41
  • 6
  • 2
    unfortunately it looks like `MongoClient.connect` doesn't return a Promise, so `await`ing it achieves nothing. You either have to work with its old-fashioned callback style API (see [this](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) for some applicable ideas), or use a more modern Promise-based library. (I don't know if one exists - I have little experience with MongoDB - but I'd be surprised if one didn't.) – Robin Zigmond Apr 17 '22 at 17:57
  • I dont want use old style. I think i code new mongodb library. I need code this project very modular. – Wraithdev3 Apr 17 '22 at 18:37
  • 1
    Well I've researched (googled, I mean!) a bit more and it looks like there is a Promise-based interface as well: see examples [here](https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/) and also [this](https://www.mongodb.com/docs/drivers/node/current/fundamentals/promises/) section. So it looks like you need to just `await MongoClient.connect(url)` and then put the logic you currently have in your callback function after that. – Robin Zigmond Apr 17 '22 at 19:03
  • You can try the code from this post (you need to add your own find query): https://stackoverflow.com/questions/68493409/mongodb-native-connections-from-nodejs-return-undefined-databases-list/68494784#68494784 – prasad_ Apr 18 '22 at 05:05

1 Answers1

-1

Maybe this works

queryDB = (collection, filter) => {
  await client.connect();
  const db = client.db(dbName);
  return db.collection(collection).findOne(filter);
}

queryDB("collection", "filter").then((err, result) => {
  if(err) throw err;
  console.log(result)
})
Emrah
  • 29
  • 1
  • 6