skip to Main Content

Cant connect to MongoDB database and store data in localhost:27017 using MongoClient.

Cant display connection result in the console (both failure and success connections).

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('/submit',function(req,res){
  console.log(req.body)

  mongoClient.connect('mongodb://localhost:27017',function(err,client){

    if(err) {
      console.log(err.message);
      res.status(500).send('Internal Server Error');
    }
    else {
      console.log('connection success')
      client.db('Sample').collection('user').insertOne(req.body)
    }
  })
  res.send('Yeah, got it !')
})

module.exports = router;

I tried to connect mongodb and store data using MongoClient. but the data neither stores in the database nor show the connection message inthe console.

when I tried to output to connection result in the console its not showing anything. its not showing either ‘connection success’ or ‘connection error’ message .The console is empty.

I want to store data using this same method if its possible with required solutions to this issue.

I also wanted to show output in the console whether the connection is success or failure.

I’m using mongodb version 7.0.4 and mongosh 2.0.2 in windows. path is set, mongo also working fine with terminal. how can I solve this issue… ?

2

Answers


  1. Your functions where you use mongo to perform requests need to be asynchronous. Those functions then return Promises which you can tackle with the .then method. Hope this helps!

    Login or Signup to reply.
  2. Try this code once:

    const express = require('express');
    const router = express.Router();
    const { MongoClient } = require('mongodb');
    
    router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });
    
    router.post('/submit', async function(req, res) {
      console.log(req.body);
    
      const url = 'mongodb://localhost:27017';
      const dbName = 'Sample';
    
      try {
        const client = await MongoClient.connect(url);
        console.log('Connected successfully to server');
    
        const db = client.db(dbName);
        const result = await db.collection('user').insertOne(req.body);
    
        console.log('Data inserted successfully:', result.insertedId);
        res.send('Data inserted successfully');
    
        client.close();
      } catch (err) {
        console.error('Error:', err);
        res.status(500).send('Internal Server Error');
      }
    });
    
    module.exports = router;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search