skip to Main Content

I’m new to node.js and MongoDB. Installed all packages as says in a YouTube tutorial. I tried a lot to connect **MongoDB **with node.js. but, there is no error messages and not connected. I have downloaded **Mongo Shell ** also. everything works perfectly, the connection message is not displaying. It works on my command prompt. But not in vs code. I’m creating a sample project with express generator. What’s wrong with my code?

Here is my code…

    var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient


/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/signup', function(req, res) {
  console.log(req.body);


  MongoClient.connect('mongodb://localhost:27017', function(err, client){
    if(err)
      console.log('error')
    else
      console.log('mongodb connected...')
  })

  
  res.send('Got it.')
})

2

Answers


    1. Check if your instance requires authentication.
    2. Check if your local instance in daemon mode
    3. Check if this URI connect on mongodb atlas
    Login or Signup to reply.
  1. Try my simple code below,
    If work it says "Connected successfully to server" in the console log
    It is only the first step…

    //const { MongoClient } = require('mongodb');
    // or as an es module:
    import { MongoClient } from 'mongodb'
    
    // Connection URL
    const url = 'mongodb://localhost:27017';
    const client = new MongoClient(url);
    
    // Database Name
    const dbName = 'myProject';
    
    async function main() {
        // Use connect method to connect to the server
        await client.connect();
        console.log('Connected successfully to server');
        const db = client.db(dbName);
        const collection = db.collection('documents');
    
       
        return 'done.';
    }
    
    main()
        .then(console.log)
        .catch(console.error)
        .finally(() => client.close());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search