Reputation: 4306
I'm learning to build API's with node and mongoose. While creating my schema I set one of the values to be unique : true
. But then again on the tutorial I am watching, the guy is checking again if the email exists in the database. Isn't this double work? If the value of email is set to be unique , why check with the findOne method if it exists? Shouldnt this unique:true
take care of this?
Upvotes: 0
Views: 61
Reputation: 1612
In almost all cases you'll encounter, it doesn't make sense for the purpose of validation to query manually to check if the value is unique. Mongoose automatically creates an unique index on the field and therefor mongodb is handling the actual validation in this case.
Even the case of error handling can easily be done like this. Still, depending on your code it could happen that there is some setup that will require a specific error handling of this case (e.g. if error handling is not done through with actual errors or the program-flow should not stop the process)
Another edge-case might be queries that circumvent the mongoose validation by using the mongodb driver directly, but as mentioned before, this shouldn't matter, as mongodb (not mongoose) will still throw an "duplicate key" error.
Finally using findOne to check for the existence of an object is not the most performant choice, as count or find().limit(1) might be more performant choices in this case.
Upvotes: 1