I am trying to get number of documents available in my collection using NodeJS. I am getting number successfully in console but it is not sending response and showing below error:
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 10 at ServerResponse.writeHead (_http_server.js:246:11) at ServerResponse._implicitHeader (_http_server.js:237:8) at ServerResponse.end (_http_outgoing.js:720:10) at ServerResponse.send (D:\Backend\aamku_con_backend\node_modules\express\lib\response.js:221:10) at D:\Backend\aamku_con_backend\routes\dealerCount.js:29:50 at executeCallback (D:\Backend\aamku_con_backend\node_modules\mongodb\lib\operations\execute_operation.js:74:5) at callbackWithRetry (D:\Backend\aamku_con_backend\node_modules\mongodb\lib\operations\execute_operation.js:122:14) at D:\Backend\aamku_con_backend\node_modules\mongodb\lib\operations\count_documents.js:36:7 at D:\Backend\aamku_con_backend\node_modules\mongodb\lib\operations\command_v2.js:90:9 at D:\Backend\aamku_con_backend\node_modules\mongodb\lib\cmap\connection_pool.js:308:13 { code: 'ERR_HTTP_INVALID_STATUS_CODE'
Below is my code:
router.get("/dealerCount", (req, res) => {
MongoClient.connect(dburl,{ useNewUrlParser: true, useUnifiedTopology: true },
(err, client) => {
if (err) {
console.log("Error", err);
} else {
const coll = client.db("Mydb").collection("Dealers");
coll.countDocuments(function(err, resp) {
if (err) {
console.log("Error", err);
} else {
console.log(resp);
res.send(resp);
}
});
}
}
);
});
How can I get total count in response?
The problem is res.send(resp);
line. It is making express think that you are sending a integer which is not allowed. Replace that with this
res.send({"value": resp});
OR
res.send(resp.toString());