Search code examples
mongodbmongoosevisual-studio-codevscode-code-runner

Vs Code: How can I use the run code command to query my database?


In Vs Code there is a play icon on the top right of the window that when clicked runs the code in the opened file. I have a development server opened on my laptop.

Can I query my Db with the run code command?

For example, I have a file with code as seen below(I am using nodejs and mongodb via mongoose):

async function getUsers(){
    try{
        let Users = await User.find({})
        console.log(Users)
    } 
    catch(err){
        console.log(err)
    }
}

getUsers()

Everytime I run the VsCode run code command I do not see any any results or error logged to the console. How can I see them? Is it possible to query the DB this way? If not, how can I test my DB queries without involving the front end?

------------EDIT------------

  1. All I see in the console is : [Done] exited with code=0 in 0.583 seconds

  2. After trying again and again I am now getting the error SyntaxError: await is only valid in async function

  3. After removing the await I am now getting the mongodb query object returned to me rather than the results.

  4. After returning the await key word and changing my code to look like below now I am getting Promise { <pending> } as the result.

    async function getUsers(){
        try{
            let U = await User.find({})
            return U;
        } 
        catch(err){
            console.log(err)
        }
    }
    
    console.log(getUsers())
    

How can I resolve the promise and see the results?


Solution

  • Use the MongoDB for VS Code extension.

    This video explains how to set it up.

    You can read more about it in the MongoDB docs.