-1

I need help with this syntax

var Category = require("../models/category");

app.get("/", function(req, res){

 var categories = findCategory();

 res.send(categories);
});

function findCategory() {
 Category.find({})
    .populate("subCategories")
    .exec(function(err, categories) {            
     if (err) {
      req.flash("error","Error while retrieving information from database");
      res.redirect("back");
     }
     return (categories);
  });
};

Result is undefine .. I do not seems to understand why

I should return this

[ { subCategories: [ [Object], [Object], [Object] ],
_id: 5b58fe38a9281b21d07fc094,
title: 'Web, IT & Software Dev',
description: 'PHP, Wordpress, HTML, JavaScript and many more',
__v: 3 },
 { subCategories: [ [Object] ],
_id: 5b58fe4aa9281b21d07fc095,
title: 'Mobile Phones & Computing',
description: 'Mobile App Development, Android, iPhone, iPad, Amazon Kindle..',
__v: 1 },]

Please Help!!!. Thanks

  • 1
    Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Aug 20 '18 at 15:30

1 Answers1

2

The main issue is that your findCategory function returns a value inside a callback, but your route calls it like a synchronous function. There are a couple ways to fix this, but I like async/await if you're using a modern version of Node.js. It would look something like:

var Category = require("../models/category");

app.get("/", async function(req, res){
    try {
        var categories = await findCategory();
        res.send(categories);
    }
    catch(e){
        req.flash("error","Error while retrieving information from database");
        res.redirect("back");
    }
});

async function findCategory() {
    return await Category.find({})
      .populate("subCategories")
      .exec();
};

Async/await is essentially a way of writing asynchronous code in a sequential way.

Another issue was that you had req.flash and req.redirect in findCategory, but if an error was ever encountered, req wouldn't have been defined.

sbrass
  • 905
  • 7
  • 12