Now creating users works,
but at the moment, we can create the same user,
with the same email address, multiple times.
And that's typically not what we want to do.
Therefore, to avoid that we do that,
in our signup handler function here,
we should check if a user for a given email already exists.
So once we connected here to the database,
before we hash the password and store the user,
I want to check if a user already exists.
I want to get a existing user by using
db.collection('users') and calling find there,
or findOne to be precise.
FindOne allows us to find one document,
and we pass a object to findOne
where we describe how to search for that document.
Key value pairs here,
and the keys are the keys we have in our documents.
So email, password, or underscore id.
And we can then search for email,
and the values are the values
we want to search for in the database.
So in this case, I want to search for documents,
which already have the email we're getting here
stored in the email field.
Now we should await this, because that it returns a promise.
And then it's either undefined,
if we did not find a user for that email,
or it is the user object.
So if it is not undefined, if it's truthy,
so if it is a object with that user data,
then we know that the user already exists.
So that's then when I want to return
so that we don't execute the other code.
And I want to send back a different response,
a response with a status of still 422, maybe,
and some data where I have a message where I say
user exists already, or something like this.
Now one thing we also want to do here,
which I haven't done before,
is close our database connection.
We should always do that.
So we should use that client
and call close once we're done here,
and also here at the bottom, of course.
We want to do that.
But now with those changes made, we should not be able
to create the same user more than once.
If I try to send this request,
or the already existing email address again,
I get a 422 error with the user exists already message.
If I use a different email address
which does not exist yet, it should work though.
And it does.
And in the database, if we refresh it,
we indeed see that every email address exists only once.
So that's now also working as it should.