繁体   English   中英

使用 nodejs 和 expressjs 在 rest api 中实现过滤

[英]implementing filtering in a rest api with nodejs and expressjs

希望你能在这里帮助我。 我将 json 存储在 mongodb 中。 此 json 包含有关手机的数据,例如 model、价格、img src。 在收到带有 url 中的价格等参数的 GET 请求后,我想将其与存储在 db 中的数据进行比较,并仅返回包含此类结果的对象。 下面提供我当前的代码(其中电话是 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);
    }
})

我不得不提到,rest 部分代码在普通的 get、post 请求上没有问题。 所以我想这个问题隐藏在这部分代码中。 我在控制台中遇到的错误:node:events:368 throw er; // 未处理的“错误”事件 ^

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

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

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

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

暂无
暂无

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

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