Home > Software engineering >  How to make query api for email that I can find data email wise for different users from mongoDB wit
How to make query api for email that I can find data email wise for different users from mongoDB wit

Time:05-03

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])

CodePudding user response:

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 using res.send(cursor).

CodePudding user response:

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.

    const handleProductPost = (event) => {
    event.preventDefault();
    const email = user.email; //before, I did not added this email when posting 
    const productName = event.target.productName.value;
    const image = event.target.image.value;
    const description = event.target.description.value;
    const price = event.target.price.value;
    const quantity = event.target.quantity.value;
    const supplierName = event.target.supplierName.value;

    const product = { email, productName, image, description, price, quantity, supplierName };

    fetch('https://back-pack-warehouse.herokuapp.com/product', {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify(product)
    })
        .then(res => res.json())
        .then(data => {
            if (data.insertedId) {
                toast('Product Added Successfully');
                event.target.reset();
            }
        });
}
  • Related