skip to Main Content
var express = require('express');
var router = express.Router();
const 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("first_name: " + req.body.first_name)
  console.log("last_name: " + req.body.last_name)
  MongoClient.connect("mongodb://localhost:27017", function(err,Client) {
  if(err) {
    console.log("ERROR");}
  else{
    console.log("CONNECTED")
  }

});
  

  res.send("HII")
})
module.exports = router;

OUTPUT
Here the data is recieved from a form but the function for checking the connection status of mongodb is not working, and no errors are showing

i am a beginer in web devolopment and dont have know much about how its connected and all.

please help me out

2

Answers


  1. Try this code once :

    var express = require('express');
    var router = express.Router();
    const { MongoClient } = require('mongodb');
    
    // Define MongoDB URL and Database Name
    const url = 'mongodb://localhost:27017';
    const dbName = 'your_database_name'; //Enter your database name here
    
    // Function to establish connection
    async function connectToDB() {
      try {
        const client = await MongoClient.connect(url);
        console.log("Connected to MongoDB");
        return client.db(dbName);
      } catch (err) {
        console.error("Error connecting to MongoDB:", err);
        throw err;
      }
    }
    
    // Establish MongoDB connection when the server starts
    connectToDB()
      .then(() => console.log("Backend connected to MongoDB"))
      .catch(err => console.error("Error connecting to MongoDB during server start:", err));
    
    // GET home page
    router.get('/', function (req, res, next) {
      res.render('index', { title: 'Express' });
    });
    
    
    router.post("/signup", async function (req, res) {
      console.log("first_name: " + req.body.first_name);
      console.log("last_name: " + req.body.last_name);
    
    
    
      res.send("User signed up successfully");
    });
    
    module.exports = router;
    
    Login or Signup to reply.
  2. var express = require('express');
    var router = express.Router();
    const 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/shibili',function(err,client){
        if(err)
        console.log('error')
        else
        console.log('database connected')
      
      })
      
    
      res.send("got it")
    })
    
    module.exports = router;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search