smit agravat
smit agravat

Reputation: 295

Mongodb query is not working i am giving value from postmen

I am trying to create app with MERN and I want to fetch data by query via api but it is not working

Here is my api code

const User = require('../models/User');
const Image = require('../models/Image');

const addImage = async (req,res,next)=>{
    const newImage = new Image({userId: req.user.id, ...req.body});
    try {
        const saveImage = await newImage.save()
        res.status(200).json('Image uploaded')
    } catch (error) {
        next(error)
    }
}

// GETPRODUCTBYID :-

const getImage = async (req,res)=>{
    try {
      const image = await Image.findById(req.params.id);
      res.status(200).json(image);
    } catch (error) {
      res.status(500).json(error);
    }
  };

// GET ALL PRODUCTS :-

const getAllImages = async (req,res)=>{
    const qNew = req.query.new;
    const qCategory = req.query.category;
    const qBrand = req.query.brand;
    try {
      let images;
  
      if (qNew) {
        images = await Image.find().sort({ createdAt: -1 }).limit(1);
      } else if (qCategory) {
        images = await Image.find({
          categories: {$in: [qCategory]}
        })
      }if (qBrand) {
        images = await Image.find({brand: 'Honda'})
      }else {
        images = await Image.find();
      }
  
      res.status(200).json(images);
    } catch (error) {
      res.status(500).json(error);
    }
  };

module.exports = Object.freeze({
    addImage,
    getImage,
    getAllImages
})

In get All products i have brand query even i am giving value it is not finding document with value instead it gives all document any help...............

Upvotes: 0

Views: 32

Answers (1)

Adem
Adem

Reputation: 61

Can you check as I can't see all the code?

  1. Have you created and started the Express server?
  2. Do you pay attention to POST or GET when sending requests on Postman?

Upvotes: 1

Related Questions