-1

I'm trying to get this function to query my db and return a few details for the selected item. It finds the items alright, but it seems to return undefined.

var recipefunc = function(name) {
      Item.find({name: name}, function(err, foundItem) {
          if(err) {
              console.log(err);
          } else {
              var image = foundItem[0].image;
              var link = foundItem[0]._id;
              var output = [image, link];
              console.log("function output:");
              console.log(output);
              return [image, link];
          }
   });
};

The console.log above outputs the correct information in an array, but doesn't make it further than that.

I'm trying to add it into this object of arrays, that is already part of a larger object.

var recipe = {
        field1: recipefunc(req.body.field1),
        field2: req.body.field2,
        field3: req.body.field3,
        field4: req.body.field4,
        field5: req.body.field5,
        field6: req.body.field6,
        field7: req.body.field7,
        field8: req.body.field8,
        field9: req.body.field9,
    };

This is the code I get returned to me, I'm only focusing on field1 at the moment, I haven't supplied data to the the others.

    recipe: 
   { field9: '',
     field8: '',
     field7: '',
     field6: '',
     field5: '',
     field4: '',
     field3: '',
     field2: '' },
Josh Kneale
  • 31
  • 1
  • 3
  • 1
    Because it's not returning anything? That `return` statement is in the `find` callback. – Bergi Feb 10 '17 at 15:43
  • @Bergi where do I have to move it to? Still learning, sorry if it's a stupid question. – Josh Kneale Feb 10 '17 at 16:05
  • Given that the database query asynchronous, it's actually impossible to immediately `return` a result. See the canonical question. – Bergi Feb 10 '17 at 16:07
  • @Bergi But I'm not returning the result immediately? It's in the callback, so once the query has been performed, do "this" with it. No? The page you have linked me too is about the return being outside of the query. – Josh Kneale Feb 10 '17 at 17:05
  • Yes, the callback will happen when the query will have been performed, but by that time `recipefunc` already had returned `undefined`. – Bergi Feb 11 '17 at 11:13

1 Answers1

0
var recipefunc = function(name, callback) {
      Item.find({name: name}, function(err, foundItem) {
          if(err) {
              console.log(err);
          } else {
              var image = foundItem[0].image;
              var link = foundItem[0]._id;
              var output = [image, link];
              console.log("function output:");
              console.log(output);
              callback([image, link]);
          }
   });
};
Artur
  • 347
  • 1
  • 2
  • 11