Why setting a callback parameter in a static method if we will not pass one?

tdd

#1

Question

In this lesson, why setting a callback parameter in a static method if we will not pass one?

Answer

To understand why we need to think about how the mongoose method works. We are using findOne, which for the documentation we can get this:

Model.findOne()
Parameters
[conditions] «Object»
[projection] «Object|String» optional fields to return, see Query.prototype.select()
[options] «Object» optional see Query.prototype.setOptions()
[callback] «Function»
Returns:
«Query»
Finds one document.

The conditions are cast to their respective SchemaTypes before the command is sent.

Note: conditions is optional, and if conditions is null or undefined, mongoose will send an empty findOne command to MongoDB, which will return an arbitrary document. If you’re querying by _id, use findById() instead.

a callback is usually implemented in methods like this to handle the found element once retrieved, in this case, the main purpose of findOne is to retrieve one document, if empty, it would be a random document if condition has been specified it will retrieve the document that matches the condition, and if there is a callback function provided, it will use it for the response. If we take a look at our construction in the lesson:

DinosaurSchema.statics.findByName = function(name, callback) {
    return this.findOne({ name: name }, callback);
};

We define our own static method for our schema, now because we want to also make sure we can use the method in our application and not just testing, we give it a callback parameter, if there is no callback, it will simply return the document as is, which is what we are testing for anyway:

const stored = await Dinosaur.findByName('Pterodactyl');

Now for our app we could do something else with that document, so a callback may be an option , if we wanted to pass a callback, lets keep in mind that the kind of function that mongoose expects has two parameters in the following order, specifically:

function(err, response){}

that way we are allowed to also handle if we are receiving an error.

Now that we know that the main reason we do not pass a callback to our static method is because we are calling it for test purposes and that we are not required to pass one since we will still be able to receive a document as a response, we are ready to play with other query methods.