generate unique random number in mongoose db without repeat?
You could generate your random number and check that it is not already stored:
function getNumber(callback){ var n = Math.floor(Math.random()*1000000000); YourModel.findOne({'number': n}, function(err, result){ if (err) callback(err); else if (result) return getNumber(callback); else callback(null, n); });}getNumber(function(error, number){ console.log(number);});
If you think this process could be called more than once in parallel, you should do some additional checks:
var alreadyRuning = false;function getNumber(callback){ if (alreadyRuning) return setTimeout(function(){ getNumber(callback); }, 10); alreadyRuning = true; var n = Math.floor(Math.random()*1000000000); YourModel.findOne({'number': n}, function(err, result){ if (err) callback(err); else { alreadyRuning = false; if (result) return getNumber(callback); else callback(null, n); } });}getNumber(function(error, number){ console.log(number); //... YourModel.insert({'number': n}, function(err, result){ if (!err) alreadyRuning = false });});
I don't believe it is possible to do this on the database, like your SQL-example.There is a ticket for adding a $rand operator to the aggregation pipeline, but that ticket is still unresolved:
https://jira.mongodb.org/browse/SERVER-30405
Still, you could create a database-function (which can have a bad performance) and store it on the server: https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/
That's not really a mongoose solution, though.