0

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

1
  • Why do you try to send a promise to the user?await result.then(data => res.status(200).send(data)) Commented Oct 22, 2022 at 18:11

2 Answers 2

0

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 });
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.