How to connect to your local MongoDB with Microsoft Visual Studio

Configurare noua (How To)

Situatie

Now that we have created a database in our local server using Mongo Compass, we want to access it via VisualSudio.

Backup

Not required.

Solutie

Pasi de urmat

First step is to choose a folder in which to work.

I created on my desktop the folder “coursework”, and in it “backend”. ( we will work in this folder). Now open CMD, and type:

  1. cd Desktop
  2. cd coursework
  3. cd backend 

and then type: npm init -y  (this line is installing the nodejs pack into your folder )

  • Next, open Visual Studio Code and:
  • Open the folder  “backend” from your desktop ( the one where you just installed the node.js pack)

Click on Terminal > New Terminal 

and type the line npm install express mongoose mongo cors –save 

(this line installs in the required packages: express,  mongoose,mongo, cors)

Create a New File  ( anyname.js )

and paste inside this code:   (and run it)

let mongoose= require(‘mongoose’)
const MONG_URI= ‘mongodb://localhost:3000/’
mongoose.connect(MONG_URI,{useUnifiedTopology:true,useNewUrlParser:true, useFindAndModify: false
    })
    const db= mongoose.connection;
    db.on(‘error’,function(err){
    console.log(‘Error occured’+err)
    })
    db.once(‘connected’,function(){
    console.log(‘connection is successful to’+ MONG_URI)
    })
    module.exports=db
this code is the link between your VS and the Server.
  • Now your VS is connected to your local server created in Mongo Compass.
  • Now you can create Databases, Collections and Documents.

You can import CSV files, delete them and do lots of things.

  • If you wish to see more on this topic, just say so in the comment section.

Tip solutie

Permanent

Voteaza

(14 din 25 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?