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.