Is it bad practice to use a mongo ObjectId as a user's id?

前端 未结 1 1911
你的背包
你的背包 2021-02-04 14:42

Seeing as this value is unique and present for all users in a mongo database, are there any particular caveats to using this as a user identifier in a web application?

P

1条回答
  •  借酒劲吻你
    2021-02-04 15:18

    ... are there any particular caveats to using this as a user identifier in a web application?

    A few that I've seen:

    1. It's not great for URLs. Twitter gives me a URL like http://twitter.com/gatesvp, with an ObjectId you get a url like http://example.com/ab12ab12ab12ab12ab12ab12.
    2. The ObjectId shards very poorly. It's not really random, it's somewhat sequential, so new users will cluster on shards rather than distribute randomly.
    3. You often need another unique identifier. Most websites have a requirement for unique e-mail or unique user name. Yes you can create a unique index on the "user name", but then you have two unique indexes, one that's useful and one that's just a random number.
    4. You will be referencing this everywhere. Your users' data will typically be spread across multiple collections all with a pointer to the "userId". Having ObjectIds (or Guids), means that you are constantly copy-pasting these big IDs everywhere and storing them in the DB.

    Particular issues I may be considering include if in the future the users need to be transferred.

    Transferred to where? Once you start storing user's data in MongoDB, the IDs are going to be the least of your problems transferring to another DB. All modern DBs can handle some form of String or Binary as the primary key ID, so your transfer should work just fine. But most of the complexity will have nothing to do with the ID.

    0 讨论(0)
提交回复
热议问题