Hello,
How can i Generate Unique Numbers for every User? i want to use it for Reference Code. thank you.
Everyone already has a unique ID, which can be found through Meteor.userId()
, Meteor.user()._id
or Meteor.users.findOne()._id
.
You can also use new Mongo.ObjectID()
to get a unique ID whenever you want.
Everyone already has a unique ID, which can be found through Meteor.userId(), Meteor.user()._id or Meteor.users.findOne()._id.
You can also use new Mongo.ObjectID() to get a unique ID whenever you want.
thank you sir. ahm. what i mean is a number that is also unique but not the _id. _id is consist of characters and numbers. I want to generate unique numbers only.
This code may possibly be a little dumb, but it will guarantee you a truly unique number every time you call uniqueNumber
var Numbers = new Mongo.Collection('numbers');
Meteor.methods({
uniqueNumber(){
var n;
do{
n = Math.floor(Random.fraction()*Number.MAX_SAFE_INTEGER);
} while (Numbers.findOne(String(n)));
Numbers.insert({_id:String(n)});
return n;
}
});
Edit: If humans are going to be using the numbers, you could change Number.MAX_SAFE_INTEGER to a lower number, like 99999, to generate a up to 5 digit number. And if you want to be sure they’re not less than 5 digits either, you could change it to: n = Math.floor(Random.fraction()*89999+10000);