0

I have a function in project

function findParentID(parentName) {
  Category.findOne({ categoryName: parentName }, function (err, foundParent) {
    var parentID = foundParent.categoryID;
    return parentID;
  });
}
module.exports.findParentID = findParentID;

and when I try to call this function, I am getting undefined in console.log() This is how I am trying to call it

var parentName = req.body.parent_name;
var parentID = findParentID(parentName);
console.log(parentID);

based on my understanding, the function is not returning any value. How do I return a value from the function?

Olian04
  • 6,480
  • 2
  • 27
  • 54

1 Answers1

2

In your code,you were trying to directly call the function which has db(async) operation.

Either use promises/async await.Once the value is returned accordingly do the consecutive operations

function findParentID(parentName) {
return new Promise((resolve,reject)=>{
  Category.findOne({ categoryName: parentName }, function (err, foundParent) {
    var parentID = foundParent.categoryID;
    resolve(parentID);
  });
});

}
module.exports.findParentID = findParentID;


var parentName = req.body.parent_name;
   findParentID(parentName).then((parentID)=>{
   console.log(parentID);
  
  });
  

Update(As per recommendation)

  var parentName = req.body.parent_name;
    Category.findOne({ categoryName: parentName }).then(foundParent => {
   
     var parentID = foundParent.categoryID;
      console.log(parentID);
    })
  
  • 1
    [There is no reason to use the Promise constructor here.](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – VLAZ Sep 15 '20 at 16:49
  • .findOne is already returning a promise. – Sheelpriy Sep 15 '20 at 16:52
  • If I have store returned `parentID` in a variable, how do I do that? while I am trying to store in a var, I am getting [object-promise] as result – Mridushyamal Barman Sep 15 '20 at 16:55
  • @MridushyamalBarman try the following code Category.findOne({ categoryName: parentName }).then(foundParent => { var parentID = foundParent.categoryID; console.log(parentID) }) – Harshit Narang Sep 15 '20 at 17:30