1

Im trying to get a product by its code id, but the result its empty array. My controller:

 export const getProductByPLU = async (req, res) => {
  const  searchPLU  = req.query;
     try {
        const product = await Product.find({ Code: { $eq: searchPLU } });
        res.json({ data: product });
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
    };

if i try to get this http://localhost:5000/products/search?3036 result is

> {
"data": []
}

I get all the products, just cant get that one specific. Simple Product:

   {
    "_id": "618a42e4801d324e3d84c16c",
    "ProductId": "868",
    "Name": "Aus Wagyu Flat WX5+",`enter code here`
     "Barcode": 2000000001630,
     "Code": 163,
     }
1
  • 1
    /products/search?code=163 , const searchPLU = +req.query.code; Commented Nov 10, 2021 at 1:11

2 Answers 2

1

If you're sending the request like this http://localhost:5000/products/search?3036 your req.query will be { 3036: '' }.

You need the URL param to be a key:value pair so the correct way to do it will be: http://localhost:5000/products/search?id=3036 this will produce { id: '3036' }

then you'll be able to get the id value by using req.query.id

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that was it ! :)
Happy I could help. Would appreciate if you accept this answer.
1

You can form your query in different ways, using:

The Query String:

An example URL in the browser: http://localhost:5000/api/library?bookid=546

This is a URL with a Query String. The bookid=546 is the query string (and this comes after the ?). And, the GET request:

app.get("/api/library", function(req, resp) {
    // req.query value will be { bookid: "5416" }
    const bookId = req.query.bookid
    // If bookId is a number in the database, first convert the bookId
    // value to a number; this is because request query param values
    // are of string type
    const bookIdNum = parseInt(bookId)
    const doc = collection.find({ bookId: bookIdNum })
    // ...
})

The Request Params:

req.params says: The req.params property is an object containing properties mapped to the named route "parameters". For example, if you have the route /user/:name, then the "name" property is available as req.params.name.

An example URL in the browser: http://localhost:5000/api/library/Mark Twain

And, the GET request:

app.get("/api/library/:author", function(req, resp) {
    // req.params value will be { author: "Mark Twain" }
    const authorName = req.params.author
    // make the database call to retrieve the book info using the authorName...
}) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.