skip to Main Content

How to know what all methods in mongoDb has an inbuilt promise in it.
eg: "updateOne() , findOne()ACCESSING INBUILT PROMISE OF "INSERTONE()" USING ".THEN"" these methods have inbuilt promises and and we can access the response using ".then" but for lots of other mongoDB methods lack this feature how can we be sure of which methods dont have inbuilt promise in them?

eg: "find()" has no inbuilt promise so we cannott perform "find().then((response)=>{})" this will give an error.
Whereas "findOne().then((response)=>{})" will work without any issue.

3

Answers


  1. This is inconsistent across the NodeJS MongoDB driver as some methods return more complex objects for manipulating the returned values. For example, .find() returns a FindCursor object which can be used to iterate over results by calling .next() repeatedly.

    I would recommend referring the MongoDB documentation for the NodeJS driver (found here, or common usage examples are here) rather frequently. The documentation is reasonably extensive and should help with issues like this.

    You can also consider using TypeScript, which I have personally found helpful for cases such as this because you can easily tell what type of object is returned from a function/method call.

    Login or Signup to reply.
  2. I would recommend referring the MongoDB documentation for the NodeJS driver (found here, or common usage examples are here) rather frequently. The documentation is reasonably extensive and should help with issues like this

    Login or Signup to reply.
  3. There is some inconsistency over the find method in MongoDB native driver in node Js. This is because the reason that the finds method returns a cursor. So what we could do here is convert that to an array using the toArray() method.

    The best solution here would be to use async await over promise chaining.
    This would provide us with a cleaner and easier syntax to work with.

    Eg :
    Let’s say we want to find all the products in the product collection. Below is a function for doing exactly that.

    const findAll=async(userId)=>{
        const userData= await db.products.find().toArray();
        console.log(userData);
        return userData;
    }
    

    Upon calling the above function we would get all the products in the product collection. Just by looking at the code, we could see that it provides a more readable syntax than chaining promises all over.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search