【问题标题】:implementing filtering in a rest api with nodejs and expressjs使用 nodejs 和 expressjs 在 rest api 中实现过滤
【发布时间】:2021-11-22 10:14:02
【问题描述】:

希望你能在这里帮助我。 我将json存储在mongodb中。此 json 包含有关手机的数据,例如型号、价格、img src。在 GET 请求中使用 url 中的价格等参数后,我想将其与存储在 db 中的数据进行比较,并仅返回包含此类结果的对象。 下面提供我当前的代码(其中 Phone 是 mongoose.model 的名称):

router.get("/:price", async (req, res) => {
    try {
        const phone = await Phone.find(c => c.price === parseInt(req.params.price));
        if (!phone) res.status(404).send('The phone with the given price was not found');
        res.send(phone);
    } catch (e) {
        res.send('Error ' + e);
    }
})

我不得不提一下,代码的其余部分在普通的 get、post 请求上没有问题。所以我想这个问题隐藏在这部分代码中。 我在控制台中遇到的错误: 节点:事件:368 投掷者; // 未处理的“错误”事件 ^

TypeError:无法读取 null 的属性(读取“价格”)。在 Postman 中我还有一个:MongooseError: Query was already executed: Phone.find({})

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    我认为您将 JS Array.find() 方法与 MongoDB find({}) 方法混淆了。 将您的 find 方法更改为:

    Phone.find({ "price": parseInt(req.params.price) });
    

    假设您的Phone 模型中有price 属性,这将找到所有price 等于req.params.price 的文档

    【讨论】:

    • 它正在工作!非常感谢!!
    • 很高兴我能帮上忙。如果这回答了您的问题,请接受此答案。
    猜你喜欢
    • 2014-11-24
    • 2014-11-20
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多