Using done() callback in Glitch

Hello!

I’ll try and make this short. So I’ve been going through the Mongoose tutorials and I am doing ok, but I feel like my biggest hangup is the whole done() callback convention. The tutorials have the basic explanation:

_// **Note**: GoMix is a real server, and in real servers interactions with_
_// the db are placed in handler functions, to be called when some event happens_
_// (e.g. someone hits an endpoint on your API). We'll follow the same approach_
_// in these exercises. The `done()` function is a callback that tells us that_
_// we can proceed after completing an asynchronous operation such as inserting,_
_// searching, updating or deleting. It's following the Node convention and_
_// should be called as `done(null, data)` on success, or `done(err)` on error._
_// **Warning** - When interacting with remote services, **errors may occur** !_

_// - Example -_
_// var someFunc = function(done) {_
_//   ... do something (risky) ..._
_//   if(error) return done(error);_
_//   done(null, result);_
_// };_

I just don’t really understand where that is coming from. For example we have in challenge 6 the following:

var findOneByFood = function(food, done) {

  Person.findOne({favoriteFoods: food}, function(err, data) {
    if (err) return done(err);
    return done(null, data);
  });
  
};

That works fine and everything, but I’m not really sure what’s going on when I am using the done callback. My understanding is that I would literally be placing some callback function (assigned somewhere else?) in place of the “done.” But I feel like that’s wrong and it’s a real callback coming from somewhere else. For example, why is it done(null, data) ? Where are those arguments getting established?

I’ve actually done a while mongoDB course on their website so the concepts of making queries and everything seem very simple, but I just feel lost with how that callback is being used/implimented and tried looking elsewhere online but can’t find anything! Help! (Please :slight_smile:)

Hi,
It seems to me too the callback function passed as ‘done’ should be defined elsewhere in the code but I’m not sure the actual tests are looking for it, which could explain why they pass on your side.
I hope someone sheds some light on this too as I’m stuck further up on these challenges.
Keep it up !
Franck

this done should be considered as a callback inside a callback,

var findOneByFood = function(food, done) {

  Person.findOne({favoriteFoods: food}, function(err, data) {
    if (err) return done(err);
    return done(null, data);
  });

we use it here because we want to define outer function findonebyfood , inside that function we used person.findone —> this gives us a callback , and if we did not pass it to the outer function the result will be null