'Add field value by Constructor.count in pre validate hook in mongoose

My Schema username is set to unique & required to false

on creating user I don't include username!

when I try to create a second user it throws error on validate because the first user has username set to null and it is a duplicate to second user's username field.

So, I tried setting the username to total number of users in collection but Count() runs in last and also does not update the username

UserSchema.pre('validate', function(next) {

const self = this;

// count() runs after pre.save()

self.constructor.count(async function(err, data) {
     var x = data
     self.username = "name"+data
    console.log(data)
});

// this console outputs before constructor.count()

console.log(this.username)
next()

});

// even self.set() returns Set is not a function inside Constructor.Count

I tried running constructor.count() through variable function so it runs before setting the username and retrieve the total number of collection from count but it still doesn't work



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source