-2

I'm trying to create a filter to stop duplication in submitting forms, I have used findone and checked if it's null returns true and vise versa, but it always returns undefined

function checkParticipant(fname, mname, lname, foname){
  Participant.findOne({
    fname: fname,
    mname: mname,
    lname: lname,
    foname: foname
  }, function(err,participant){
    if(participant == null){
      return true;
    }else{
      return false;
    }
  });
}
Zim
  • 1,457
  • 1
  • 10
  • 21
Hama Saadwn
  • 743
  • 2
  • 9
  • 16

5 Answers5

0

Try using

function checkParticipant(fname, mname, lname, foname){
  Partiipant.findOne({fname:fname, mname:mname, lname:lname, foname:foname }).then( participant => (
   if(participant) return false
   else return true;
))
}

FindOne returns a promise so you`d have to subscribe to it to get the data.

Liondj
  • 48
  • 9
0

Your checkParticipant function does not contain a return statement. Hence it will return undefined.

0

A function returns undefined if a value was not returned.

Please check MDN before posting.

leonardofed
  • 936
  • 2
  • 9
  • 24
0

The problem is that you are trying to return from an asynchronous function. This is not possible. Check this answer on how to solve it

itsundefined
  • 1,409
  • 2
  • 12
  • 32
0

Nothing wrong with code you have returned. Its just about concept of Javascript callback function.

function timeOut()
{ 
  setTimeout(function(){ return true; })
};

timeOut(); // returns undefined

Executing this function returns undefined becuase, the query has callback function which runs in different context and returns nothing that means undefined.

So to solve your problem, you need to update the code as follows if your ORM supports the promises.

function checkParticipant(fname, mname, lname, foname){
   return Partiipant.findOne({fname:fname, mname:mname, lname:lname, foname:foname 
}).then( participant => (
   if(participant == null)
   {
       return true;
   }
   else return false;
  ))
}

Hope this will solve your problem.

Saurabh Ghewari
  • 689
  • 3
  • 8