繁体   English   中英

Mongodb find 查询返回空数组

[英]Mongodb find query returns empty array

我试图通过其代码 ID 获取产品,但结果是空数组。 我的控制器:

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

如果我尝试获取此http://localhost:5000/products/search?3036结果是

> {
"data": []
}

我得到了所有的产品,只是无法得到特定的那一种。 简单产品:

   {
    "_id": "618a42e4801d324e3d84c16c",
    "ProductId": "868",
    "Name": "Aus Wagyu Flat WX5+",`enter code here`
     "Barcode": 2000000001630,
     "Code": 163,
     }

您可以使用以下不同方式形成查询:

查询字符串:

浏览器中的示例 URL: http://localhost:5000/api/library?bookid=546

这是一个带有Query String的 URL。 bookid=546是查询字符串(它在? )。 而且,GET 请求:

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

请求参数:

req.params说: req.params属性是一个包含映射到命名路由“参数”的属性的对象。 例如,如果您有路由/user/:name ,则“name”属性可用作req.params.name

浏览器中的示例 URL: http://localhost:5000/api/library/Mark Twain

而且,GET 请求:

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

如果您发送这样的请求http://localhost:5000/products/search?3036您的req.query将是{ 3036: '' }

你需要 URL 参数是一个键:值对,所以正确的方法是: http://localhost:5000/products/search?id=3036这将产生{ id: '3036' }

那么你就可以通过使用req.query.id来获取 id 值

也许你可以试试Number(searchPLU)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM