API Design – Is It Bad Practice to Generate IDs for Non-Existent Database Objects?

apiapi-designmongodbmongoosenode.js

Here is the situation:

There is a Mongo database A and there is Mongo database B.

There is a business concept/Mongo object that is called someModel which exists on one of database B's collections.

Here is the question. The way we generate this someModel is based on other object's data from database A. And there are times when we want to load all of the existing someModels (actually existing objects in database B) and non-existing ones which are just a conglomerate of data from database A's collections (as mentioned).

Now for the existing someModeles we have a Mongo id which is unique and has been generated at the time of creation, however for non-existing someModels we don't have an id yet. The reason we need it is for identification/matching purposes (between front end and back end).

Bottom line is that I am thinking of generating an ID through Mongoose and have a fully populated DTO at all times even if the ID is going to be temporary (until it is saved) and only used for identification/matching purposes – however once saved the "temporary id" will now become permanent.

I purposefully made it very abstract so that it sounds like a general problem instead of making it business specific but if you guys need more details please ask and I will surely provide them.

So that's the question – if generating ids for a non-existing object in the database is bad practice in this specific context.

Thank you guys and appreciate your time and support!

Best Answer

As often, it depends. Since you asked for a general answer, I am trying to give one independent from the specific technology, here MongoDB.

If the allowed domain range for the IDs is huge, and you are not letting your database generate several millions of IDs per second, so the risk of running out of available IDs in a reasonable amount of time is small, then you can take those IDs and use them for whatever you want (even if that means you use them only temporarily and then throw them away).

On the other hand, when the above preconditions are not fulfilled, you need to be careful not to come to a point where you run out of IDs or get ID collisions.

For example, using GUIDs as IDs (which use a domain range of 128 bit numbers) makes it very unlikely to get ID collisions as long as you do not create a huge amount of them in a short time, especially when you can restrict the collision tests for your special use case.

Also be careful that domain ranges which look huge today might not look so huge tomorrow (best example is the IP V4 protocol, where the available adresses have become scarce over the years).

Related Topic