Each user has a unique ID and an email and password. Of course, email is also unique.
Currently, I have a id field in my mongoDB collection of user. For example, below is a document of a user.
{
_id: objectID(12345678),
id: 1,
email: [email protected],
password: xxxxxxxxxx
}
I am thinking to get rid of the id field, and use the _id to store my user id. For example:
{
_id: 1,
email: [email protected],
password: xxxxxxxxxx
}
Is that a good idea? Any danger of doing so? I think this is going to reduce the complexity and redundancy.
2
Answers
Yes, what you think is right. You should use the automatically generated
_id
from MongoDB to identify the user uniquely, there is no need for writing a separate id of your own.Two advantages :
This is a generic topic not only related to MongoDB. Google for "surrogate key vs natural key" or "surrogate key vs primary key", you will find many articles with pros and cons for both sides.
You say "email is always unique" – is this really true? Also in future when your application evolves?
In your case I would suggest to use a dedicated field instead of the
_id
field. Think about potential situations now and in the future:_id
field in a special way. Maybe they suppress it or run other "stupid" stuff, e.g. execute_id.getTimestamp()
internally and fail._id
cannot be modified!