Skip to content
Advertisement

How to return object from MongoDb database in findOne method

sorry if it’s easy mistake, I’ve not so much experience in JS, I’ve tried a lot of ways and I can’t resolve this problem.

I can find and print my object from database, but I can’t return it to my main method.

My main method (it’s in another file than methods to database):

JavaScript

and (before tries to debug this) my “object” is undefined. Take a look on two methods I’ve used:

JavaScript

and last:

JavaScript

I tried something with ‘then’ too:

JavaScript

In both examples of getFirstObjectFromBase console.log(result) print good object, but program just stop after this and I can’t return this JSON to main method.

Thank you in advice 🙂

Advertisement

Answer

Problems in your code:

  • Inside connectAndReturnWithFunction function, you never call resolve()

  • async functions always return a Promise, so you don’t need to create one yourself using the Promise constructor. You never use await keyword inside connectAndReturnWithFunction function, so making it async is unnecessary.

  • Inside connectAndReturnWithFunction function, inside the the callback function of mongoClient.connect, in case of an error, you log a message indicating that connection to database couldn’t be established but the last two lines of code

    JavaScript

    will still execute. You probably meant to add those two lines inside the else block.

    JavaScript

Reasone why object is undefined because inside the connectAndReturnWithFunction, you never call resolve(), which is needed to resolve the Promise with the data from the database.

To fix the problem, pass the resolve() and reject() functions to the callback function of connectAndReturnWithFunction function.

JavaScript

to

JavaScript

and inside the getFirstObjectFromBase function, call the resolve() function, passing in the result as an argument. In case of an error, call the reject() function, passing in the error object as an argument.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement