I am new in backend development with MongoDB, NodeJS and frontend development with React-JS.
I wanted to make an API endpoint that find the data from MongoDB and filter by user email address when user logged in the system. My Login system is completely okay. But The problem is When I try to retrieve data from client side that time data is not showing(fetching) on the UI. It founds and empty array. I want to know what is the problem in my code.
Here is my API Code for backend:
app.get('/myproducts', async (req, res) => {
const email = req.query.email;
const query = { email: email };
const cursor = inventoryCollection.find(query);
const myProducts = await cursor.toArray();
console.log(myProducts);
res.send(myProducts);
});
Client Side Code:
useEffect(() => {
const getMyProducts = async () => {
const email = user?.email;
console.log(email);
const url = `http://localhost:5000/myproducts?email=${email}`;
try {
await fetch(url)
.then(res => res.json())
.then(data => setProducts(data))
} catch (error) {
console.log(error?.message)
}
}
getMyProducts();
}, [user])
2
Answers
I solved it, There was a mistake from me. When I added product in my inventory that time I did not save my email in database with that post. After save my email in database, now I am able to filter product by email and also displaying on UI.
The
toArray
function exists on the Cursor class from the Native MongoDB NodeJS driver. The find method in MongooseJS returns a Query object.In this case, you can directly log or send your
cursor
usingres.send(cursor)
.