When you use MongoDB as a database, do you use your own _ id field as the primary key (foreign key) or use your own defined id?

recently working on a node project, using mongoDB in the background.
found that there is a default primary key _ id, in MongoDB. I can also set up a sequence myself, like mysql.
if you use the default primary key, the returned JSON string uses _ id, which is not very friendly to the front end.
the question is, do I need to use a custom primary key, and what are the considerations?

Oct.30,2021

generally you don't have to define your own primary key, unless you have special requirements


there are no specific requirements for you not to use ObjectId as the primary key. So if you have a better choice, just use your own primary key, there's nothing wrong with it.
the problem is that this _ id must be globally unique, and how to achieve global uniqueness is not an easy task, so many people fall into the misunderstanding of using self-increasing ID. Self-adding ID is a very bad choice, for reasons I explained in . If you can achieve global uniqueness in your system and avoid the trap of self-adding ID, it would be nice to customize it.

Menu