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?

1

2 Answers 2

3

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
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.

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.