badal16
badal16

Reputation: 509

Is there mongodb query which will insert document if field is unique otherwise execute custom function

Trying to create an activation code which should be unique, but it only consists of specific characters. So, this is solution which i build

function findByActivationId() {
   return Activation
        .findOne({activationId})
        .lean()
        .exec();
}
let activationId = buildActivationId();
while (await findByActivationId(activationId)) {
    activationId = buildActivationId();
}

This makes too many db calls, is there any better way to make query to mongodb?

Upvotes: 0

Views: 58

Answers (1)

Matrzak
Matrzak

Reputation: 104

Well, the major problem of checking if key is unique is based on how you are creating those.

Choose the best way for you to avoid bunch of problems later.

Your own generated string as a key

Well, you can do this but it's important to understand few disclaimers
If you want to generate your own key by the code and then compare if it is unique in the database with all other currently created it can be done. Just create key by your algorithm then select all keys from db and check if array of selected rows contains this freshly created string

Problems of this solution
As we can see we need to select all keys from DB and then compare each one to freshly created one. Problem can appear when your database is storing big amount of data. Every time application have to "download" big amount of data and then compare it to new one so in addition this might produce some freezes.

But if you are sure that your database will store not that much amount of unique rows, it is cool to work with.
Then it is important to create those keys properly. Now we talking about complexity, more symbols key is created from, harder to get same ones.

Shall we take a look at this example?

If you are creating keys based on letters a-z and numbers 1-9 and the length of key is for example 5, the complexity of this key is 35^5 which generates more than 52 milions possibilities. Same keys can be generated but it is like a win on a lottery, almost impossible
And then you can just check if generated key is really unique, if not. (oh cmon) Repeat.

Other ways

  1. Use mongodb _id which is always unique
  2. Use UNIX timestamp to create unique key

Upvotes: 1

Related Questions