Mohamed Daher
Mohamed Daher

Reputation: 709

Mongoose countDocuments() returning query

I am trying to count the number of Loans a specific user has from an API call. The Loans schema has a user field with the id of the related user. To count the loans:

router.get('/loans/count:id', async (req, res) => {
  try {   
      const count = Loans.countDocuments({ user: req.params.id });
      console.log(count);
      res.json({ count: count });
    
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

I just need the result to be a number with the count of the number of documents. How can I do that?

This is the error:

Error: Request failed with status code 500 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61)

Upvotes: 0

Views: 84

Answers (1)

Parth Shah
Parth Shah

Reputation: 1475

You have to return the response object like so:

router.get('/loans/count:id', async (req, res) => {
  try {   
      const count = Loans.countDocuments({ user: req.params.id });
      console.log(count);
      res.status(200).send({count: count});
    
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

Upvotes: 1

Related Questions