Okechukwu Mba Okechukwu Mba - 3 months ago 7
Javascript Question

In the event of a "no-result found" scenario in Express, how can i output my choice error message to the browser without displaying an empty array []

var express = require('express');
var router = express.Router();
var Questionnaire = require('../models/questionnaire');




router.get('/', function(req, res, next) {
Questionnaire.find().sort('username').exec(function(error, results) {
if (error) {
return next(error);
}
// Respond with valid data
res.json(results);
});
});
router.get('/:questionnaireId', function(req, res, next){
Questionnaire
.where({username: req.params.questionnaireId}, {featured: true})
.where({featured: true})
.exec(function(error, results){
if (error) {
return next(error);
}
if (!results) {
res.send(404);
}
res.json(results);
});
});


module.exports = router;

In the event of a "no-result found" scenario in Express, how can i output my choice error message to the browser without displaying an empty array []. Each time i run a query with Express framework, my browser always displays this empty array [] when result is not found or user not found. How can i get around this?

Mtz Mtz
Answer
[...]

if (error) {
  return next(error);
}

// Check for empty results
if (!results.length) {
  results = { ... }; //custom response object
}

// Respond with valid data
res.json(results);

[...]

...not sure on the if condition but you get the idea.