skip to Main Content

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


  1. 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 :

    1. Auto-generated ids are always unique, so there is no problem of redundancy(repetition)
    2. It is easy to maintain.
    Login or Signup to reply.
  2. 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:

    • Some client drivers may handle _id field in a special way. Maybe they suppress it or run other "stupid" stuff, e.g. execute _id.getTimestamp() internally and fail.
    • A user may request to change his email. The _id cannot be modified!
    • You may have the requirement to merge several accounts into a new one
    • You may need more than one email for an account (e.g. for password verification/reset)
    • What happens when an account is deleted? For regulatory or other reason you may not delete the data physically from your database, you just want to lock the account. But then the email is still blocked for other uses.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search