skip to Main Content

Here is my Controller

    const getCountofCenters = async (req, res) => {
        
        const result =  Center.countDocuments();
            
        await result.then(() => res.status(200).send(result))
            .catch((err) => {
                res.status(200).send(err)
            });   
    }

This is the Api call

    router.get("/count", CenterController.getCountofCenters);

This is the output which I get from the Postman test, empty array

    {}

enter image description here

2

Answers


  1. Try this:

    const getCountofCenters = async (req, res) => {
      try {
        const result = await Center.countDocuments();
        return res.status(200).json(result);
      } catch {
        return res.status(400).json({ success: false });
      }
    }
    
    Login or Signup to reply.
  2. model.countDocuments returns a promise that you need to resolve so you can get the value of count
    so the correct implementation on this within an async function is

    await Center.countDocuments()
    

    then sequentially you can return the response

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search