Nedzny
Nedzny

Reputation: 21

Mongodb find query returns empty array

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,
     }

Upvotes: 1

Views: 1196

Answers (2)

niiir
niiir

Reputation: 377

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

Upvotes: 1

prasad_
prasad_

Reputation: 14287

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...
}) 

Upvotes: 1

Related Questions