How to know what all methods in mongoDb has an inbuilt promise in it. eg: "updateOne() , findOne()" 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.
CodePudding user response:
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.
CodePudding user response:
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
CodePudding user response:
There is some inconsistency over the find method in mongodb native driver in node Js.This is because of the reason that find 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 more cleaner and easier syntax to work with.
Eg : Lets 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.