I am working on a small shopping site using nodejs and mongodb. I have been able to store and retrieve data from my database. However, I can't get this particular function to work which is supposed to retrieve products from user cart. The products are retrieved into the then() block, but when i try to return or print the products by performing some operations in the products, i get output as Promise { pending }.
Before marking this question as duplicate(which it is not, but if you think it is), atleast help me with solve this.
const productIds = this.cart.items.map(eachItem => {
return eachItem.pid;
}); //to get product IDs of all the products from the cart
const cartData = db.collection('products') //db is the database function and works fine
.find({_id: {$in: productIds}})
.toArray()
.then(products => {
console.log(products); //all the products are printed correctly
products.map(eachProduct => {
return {
...eachProduct,
quantity: this.cart.items.find(eachCP => {
return eachCP.pid.toString() === eachProduct._id.toString()
}).quantity //to get the quantity of that specific product (here eachProduct)
};
})
})
.catch(err => {
console.log(err);
});
console.log('cartData: ', cartData); //but here it prints Promise /{ pending /}
I can't understand why i get Promise { } as output although i get the data from the database successfully in the then() block. Sorry for the messsy code btw. I'm new to mongodb and don't have so much knowledge about promises too.