简体   繁体   中英

What does unique do in mongoose

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?

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 (eg 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.

Not necessarily!

A root user can add or remove any documents' values directly from mongoDB API without going through validators!

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM