3

i want to generate a random number which should not be repeated based on the numbers from my mongoose db, i don't wanna use this for a unique number:

Math.floor(Math.random()*1000000000)

i found this answer which is in php here

SELECT FLOOR(RAND() * 99999) AS random_num
FROM numbers_mst 
WHERE "random_num" NOT IN (SELECT my_number FROM numbers_mst)
LIMIT 1

how can i do that but in mongoose?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
gpbaculio
  • 5,693
  • 13
  • 60
  • 102
  • possible dup of https://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100/2380113 – AZ_ Jun 03 '19 at 09:26

2 Answers2

2

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
    });
});
virgiliogm
  • 946
  • 7
  • 15
0

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.

BenSower
  • 1,532
  • 1
  • 13
  • 26