0

My project is to basically create users in a database and store information about exercise. I'm using mongodb and express.

I am struggling to understand the way the course was teaching me, which was with functional expressions and using the done() callback.

app.post('/api/users', (req, res)=>{
  const userRequest = req.body.username;
  
  if(userRequest === '' || undefined) return;

  console.log('requesting to create user ' + userRequest);

  const findByName = (userRequest, done) => {
    User.find({user: userRequest}, (err, userFound)=>{
      if(err) return console.error(err);
      console.log(`${userRequest} already exists`);
      done(null, userFound);
    });
  };
  
})

here so far I'm just trying to begin by creating a user. I want to first check if that user already exists. How do I check the results of this function? I've written it the way the course taught me I just don't understand it. I don't know what the done() callback does.

cnelson720
  • 39
  • 6
  • 2
    Pass `findByName` a callback, and inside that callback you can check it. Note that the current implementation is broken because it doesn't call the callback with the error is there's a problem - you should do `done(err)` if it exists. On the outside: `findByNam(req, (err, result) => { if (err) /* handle err */ else /* handle result */` – CertainPerformance Aug 07 '22 at 23:03
  • 1
    Hey @cnelson720, seems like you're looking for someone to talk it through with and try to clear up some of the confusion (rather than being stuck on something specific). Would you like to get on a zoom call and talk it through? – Rocky Sims Aug 07 '22 at 23:10
  • 1
    @CertainPerformance I got it! thank you! I totally wasn't understanding how to use a functional expression. – cnelson720 Aug 07 '22 at 23:34
  • I did this after declaring the expression above my post request `findByUsername(req, (err, result)=>{ if(err){ console.log(err); } else { if(result.username === userRequest){ console.log('That username already exists'); } else { console.log('create user') } } })` – cnelson720 Aug 07 '22 at 23:36
  • also changed the method to findOne instead of find because it kept giving me an array as a result. – cnelson720 Aug 07 '22 at 23:37

0 Answers0