Home > Software design >  implementing filtering in a rest api with nodejs and expressjs
implementing filtering in a rest api with nodejs and expressjs

Time:11-23

hope you could help me here. I have json stored in mongodb. This json contains data about phones such as model, price, img src. Having got GET request with parameters such as price in url, I'd like to compare it with data stored in db and return only objects which contain such results. Below providing my current code (where Phone is a name of 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);
    }
})

I have to mention that rest part of code is working with no problem on ordinary get, post requests. So I suppose that problem is hiding in this part of code. The error I've got in console: node:events:368 throw er; // Unhandled 'error' event ^

TypeError: Cannot read properties of null (reading 'price'). In Postman I have another one: MongooseError: Query was already executed: Phone.find({})

CodePudding user response:

I think you are confusing the JS Array.find() method with the MongoDB find({}) method. Change your find method to be like this:

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

Assuming you have the price property in your Phone model, this will find all documents that price equals to req.params.price

  • Related