Home > front end >  How to query a Mongo collection from inside of the its own Schema method?
How to query a Mongo collection from inside of the its own Schema method?

Time:10-02

In this method, I want to generate a random username for my users when users register. And, I need to check if the generated username is already in use or not.

So, I need to query the 'User Collection'. I couldn't find how to query User Collection from inside of its method.

this. key, mongoose.Collection or UserSchema always ends up with this error;

TypeError: mongoose.Collection.find is not a function

My UserSchema is something like this;

const UserSchema = new Schema({
    name: {
        type: String,
        required: [true, 'name can not be empty'],
        default: ' '
    },
    publicUsername: {
        type: String,
        required: true
    }
})

And finally, the method;

UserSchema.methods.generateRandomUserName = async function(){
    // Generate a random username
    
    // Find if username already is in use. But, how???
    let user = await mongoose.Collection.find({ publicUserName: username })
    if(user){
        // Generate again if username is in use
    }
    
    this.publicUsername = username
    return username
}

Can someone help me, please?

CodePudding user response:

You should be able to access the collection through mongoose.model():

UserSchema.methods.generateRandomUserName = async function(){
    
    const user = await mongoose.model('User').find({ publicUserName: username })
    // rest of your code
}

See this example in the docs: https://mongoosejs.com/docs/guide.html#methods

  • Related