'MongooseError: Query was already executed: Users.find({ username: 'b' })

Code block:

export const getFollowers = async (req,res) => {
                console.log(req.body)
                const profilename=req.body.profilename
                const followingarray = []
              
                try{
             await userModel.find({username:profilename},async (err,data)=> {
                const following = data[0].following
         
              
                following.map(async(whoimFollowing)=>{
                  
                await userModel.find({username:whoimFollowing},async (err,whoimFollowingdata)=> {
                       console.log(whoimFollowingdata) 
                       followingarray.push(whoimFollowingdata)
                    
                    })
        
                })
           
             }).then((res)=> {
           
             })
                }catch(e){
                   
                }
            }

When I added await to the UserModel.find Thats when this error was caused, How Can I Stop This Error From Happening?



Solution 1:[1]

the function itself is a callback so adding the async to the getFollowers() is what is causing the error. Remove the async with the try and catch from the getFollowers() and the code will work.

export const getFollowers = () => {
    console.log(req.body)
    ...
    ...
    userModel.find({...,async (err,data) => {...}})
}

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Andrea Olivato