Answer the question
In order to leave comments, you need to log in
NodeJS + Mongoose. How to generate unique document field values?
Hey! There is a task - to produce instant registration of users when entering only an e-mail. That is, a person enters his mail, and immediately enters his personal account, simultaneously receiving a letter with a temporary password and other instructions, he is also automatically assigned a username.
The model has two fields (both unique and required), "username" and "email". The e-mail is saved as is (after making sure that other documents do not have such an address and other checks), but the username must first be checked for uniqueness, and if such a username has already been used, a new one is generated, with a number (username_N). Then again there is a check for uniqueness, and if everything is OK, it is saved, if not, then username_N + 1 is generated again, etc.
Until something smarter came to mind, how to take from the collection all documents that have username = username. *, then loop through all the selected ones, and compare with username_N until a free name is found.
Answer the question
In order to leave comments, you need to log in
The current method is not secure. You need to do an atomic operation on the increment.
In mongoose, this is done with findOneAndUpdate.
An example code would be the following:
UserSchema.pre "save", function(next) {
var self = this;
UrlNameCounter.findOneAndUpdate({username: this.username}, {$inc: {count: 1}}, {upsert: yes},
function(err, counter) {
if (counter.count > 1) {
self.username = self.username + "-" + counter.count;
}
})
}
If all usernames are essentially in order, then why not just make one query to MongoDB, taking into account RegExp in findAll (), then just add +1 to the last counter.
Option number 2, make the postfix field in the model, if the username matches, a new unique postfix will simply be generated (again, by checking not with requests, but already from the selected postfixes.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question