Why are there multiple arguments in the mongoose statements with functions?

Tell us what’s happening:
I have completed the task, but I do not understand why it works the way it does. I merely copied over the solution without really understanding it.

The main thing, that I do not understand, is what the role of the second argument done or function with its two arguments err and personFound is. It’s probably something that I should have learned earlier about JavaScript. But I did not.

const findPeopleByName = (personName, done) => {
  Person.find({name: personName}, function (err, personFound) {
    if (err) return console.log(err);
    done(null, personFound);

Can you help me understand?

Your project link(s)
solution: https://boilerplate-mongomongoose.mseibert.repl.co
Invitation link: https://repl.it/join/xgzbxgas-mseibert

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.192 Safari/537.36.

Challenge: Use model.find() to Search Your Database

Link to the challenge:

You may find this documentation helpful.

Try to “expand” that piece of code and write it in a way that is clear to you.

1 Like

Because database operations are asynchronous (they take some time to complete), the next step cannot happen before the previous is finished. Let me rewrite the code:

const findPeopleByName = (personName, done) => {
  Person.find({name: personName}, findCallback);

function findCallback(err, personFound) {
    if (err) return console.log(err);
    done(null, personFound);

The .find method requests some data from the database, and once that data has arrived, it executes the callback function. It’s a convention in mongoose that all callbacks get passed two parameters, where the first is a possible error and the second the result:

callback(error, result)

So, there’s three function calls happening here:

  • find runs, and once it has a result, it calls findCallback with (error, result) as parameters
  • findCallback runs, checks if there’s an error, and (since there was none) calls done with (null, result) as parameters
  • done runs and does whatever it does (it’s not a mongoose function, I think it’s used by testing tools like Mocha or Chai, which the FCC tests are likely written with)
1 Like