0

I create my own primary key for mongodb collections in my node js app. In order to make sure generated key is unique I have to check if a collection by that generated key does not exist already. This is the code but its not working due to synchronous call:

let id = makeid()
let unique = false
$this = this
while(!unique) {

    try {
    property.findById(id, 'proptype', function (error, property) {
        if (error) { 
             console.log('not found, generated key is unique')
            $this.unique = true
        } else {
            $this.unique = false
            $this.id = makeid()
        }
      })
    } catch(e) 
    {
        console.log('exception: ' + e)
    }
}

How to fix this issue? I am looking for answer with working code. What happens is that it becomes infinite loop and each loop executes the query repeatedly.

2 Answers 2

1

try this

const uniqueCheck = async () => {
    let id = makeid();
    let unique = false
    $this = this
    while (!unique) {
        try {
            const property = await (property.findById(id, 'proptype').exec());
            if (property) {
                $this.unique = false;
                $this.id = makeid();
            } else {
                $this.unique = true
            }
        } catch (e) {
            console.log('exception: ' + e);
            $this.unique = true
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should use objectId:

var ObjectID = require('mongodb').ObjectID;

and to generate use: new ObjectID()

The collision probability will be very very low: document

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.