-1

Probably missing something simple here but cant for the life of me figure out why the below function is returning undefined.

  var isOrphanEan = function isOrphanEan (ean) {

    Products.findOne({
      'ean': ean
    }, function (err, product) {
        return product.orphan;
    });
  }

  isOrphanEan(12345); //returns undefined

example of product

{ 
_id: 55ad6b442afbebe82d077a04,
  orphan: true
  }

edit:

console.logging product returns:

{ _id: 55ad6b442afbebe82d077a04,
  ean: 4006643097328,
  aw_product_id: 3295182687,
  product_name: 'Multipower Shaker Neutral',
  product_brand: 'Multipower UK',
  product_description: '',
  img_sml: 'http://images.productserve.com/noimage.gif',
  img_lrg: '',
  rating: '',
  merchant_id: 2926,
  price_current: 'GBP4.99',
  price_rrp: '',
  aff_link: 'http://www.awin1.com/pclick.php?p=3295182687&a=234945&m=2926',
  direct_link: 'http://www.multipower.com/uk/product/multipower-shaker-09732/neutral',
  merchant_product_id: '09732',
  aw_image_url: '',
  orphan: true,
  created_at: Mon Jul 20 2015 22:42:28 GMT+0100 (BST),
  updated_at: Thu Oct 08 2015 23:20:35 GMT+0100 (BST),
  __v: 0 }
Geraint
  • 3,314
  • 3
  • 26
  • 41
  • What happens when you `console.log(product)` ? It may just be that `Products` is not finding any item given the search criteria. – David Li Oct 12 '15 at 22:31
  • 1
    You aren't returning anything, so it returns undefined. – MinusFour Oct 12 '15 at 22:31
  • Is the `ean` property stored as integer? Maybe try ean.toString() when you search. – Travis Oct 12 '15 at 22:32
  • 1
    Ohhh @MinusFour is right. You need to use a callback function in isOrphanEan since `Products` is fetching your item asynchronously. – David Li Oct 12 '15 at 22:33
  • `isOrphanEan` should take a callback that is called when `Product.findOne` has completed, rather than returning a value. – joews Oct 12 '15 at 22:33
  • @joews i would surmise this is an even better one: http://stackoverflow.com/questions/6180896/how-to-return-mongoose-results-from-the-find-method – Daemedeor Oct 12 '15 at 22:38

2 Answers2

1

Use callbacks approach to cope with async responses:

var isOrphanEan = function isOrphanEan (ean, cb) {

    Products.findOne({
      'ean': ean
    }, cb);
}

  isOrphanEan(12345, function(err, product) {
     console.log(product.orphan);  
  });
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
-1

You are using a callback. Function isOrphanEan() does not return anything, rather findOne() will call the callback when the data becomes available. You need to process you product.orphan in the unnamed callback.