Having trouble establishing a connection with Mongo.Client on localhost 27017 for MongoDB

Encountering issues with connecting to MongoDB database and storing data in localhost:27017 using MongoClient.

Unable to display connection results in the console for both successful and failed 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;

Attempting to connect to MongoDB and store data using MongoClient but facing challenges as data is not being stored in the database nor is the connection message appearing in the console.

Despite trying to output the connection result in the console, no messages such as 'connection success' or 'connection error' are displayed. The console remains empty.

Looking for a solution to resolve this issue while continuing to store data using the same method.

Additionally, seeking assistance on how to show output in the console indicating whether the connection was successful or if an error occurred.

Running mongodb version 7.0.4 and mongosh 2.0.2 on Windows with correct path settings, where mongo functions properly through the terminal. How can I troubleshoot and solve this problem?

...

Answer №1

It is important to ensure that your functions utilizing mongo for requests are asynchronous. By returning Promises from these functions, you can effectively manage them using the .then method. I trust this information proves valuable to you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP query Ajax navigation

UPDATED I have made progress with processing both menus in "process.php" and displaying the queries in index.php. process.php <?php $menu1 = $_POST["menu1"]; $menu2 = $_POST["menu2"]; if($menu1 == 0) { $sql = "SELECT * FROM Language WHERE ID = " ...

Experience the simplicity of running basic Javascript Scratch code within IntelliJ IDEA Ultimate

Is there a straightforward way to run and debug a basic JavaScript code in IntelliJ Idea Ultimate without the need for additional setup like creating an HTML file or npm project? I'm looking to avoid boilerplate tasks and wondering if there's an ...

Transferring PHP variables to Javascript variables

I'm working on a basic php script that updates specific elements of a game through JavaScript. I've encountered an issue where the variable data doesn't seem to transfer when passing them from the script to the game using forms. Currently, t ...

Utilizing JavaScript For Loops for Code Repetition

Apologies for the ambiguous question title - struggling to articulate this properly. Essentially, I have some JavaScript code that I am looking to streamline by using a for loop. $('.q1').keyup(function () { if ($.inArray($(this).val().toLo ...

Secure User Validation Using ExpressJS and CouchDB

I am currently working on implementing a CouchDB User login into my express app using a frontend form and storing the login information in the session. Here is what I have done so far: In my app.js file: var express = require('express'); var co ...

Async/Await mishap

Could someone please explain why the code below is printing a blank result? I was expecting it to print "done" since I thought the await keyword would make the program wait for the promise to be resolved. Appreciate any help provided! let message = &apos ...

unable to apply angular measurement inside quotation marks

What is the reason for this issue: <ul class="dropdown-menu"> <li ng-repeat="choice in dropDownItems"> <a class="btn" ng-click="mnuClick('{{choice}}')">{{choice}}</a> </li> </ul> However, this code wo ...

Does binary search maintain its usual efficiency?

Does binary searching remain efficient and effective if an array inherits from an object? ...

tagit: update the label's value

I've been utilizing the jquery ui plugin https://github.com/aehlke/tag-it to incorporate tagging functionality into my project. This is how I am creating tags: $("#Input").tagit("createTag", "ABC"); My goal is to append additional text to the labe ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

Steps to retrieve an image from the Vue src directory using JavaScript

I am working on a Vue app and I need to access some image files from an included JS file for different purposes, such as adding images to a canvas element. Usually, this task is simple with code like the following: function getImage() { let img = new Im ...

"Observed Issue: Ionic2 Array Fails to Update in HTML Display

I am struggling with updating an array in Ionic2 and Angular2. I have tried updating it on the front end but it's not working, even though it updates perfectly on the backend (ts) as confirmed by checking the console. I need assistance with this. Her ...

mean.js utilizes require without the use of var

Question about the default meanjs app generated by yeoman. In the express.js file, there is a line of code: // Globbing model files config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) { require(path.resolve(modelPath) ...

Preserving the "height" declaration in jQuery post-Ajax request (adjusting height after dropdown selection loads product information, resetting heights of other page elements)

Looking for a way to set a height on product descriptions using jQuery? Check out the solution below: https://www.example.com/product-example Here is the code snippet that can help you achieve this feature: $(document).ready(function() { var $dscr = $ ...

Guide to updating the object value within an array in React

Is there a way to toggle the value of a specific object key called "clicked" to true using the spread operator in React? I want to be able to press a button and update the object's value. let questions = [ { title: "What do I want to learn ...

Guide on how to point to a React JS application via Node JS server on the same server

I am working with two separate React JS applications and need to direct users to the appropriate application based on the URL. For example: app.get('/' , (req,res,next) => { // Redirect to the first SPA }); app.get('/admin' , (r ...

Utilizing Angular2 to access NPM package (Googleapis)

I am currently developing an Angular2 application that utilizes Webpack for the build process. I want to implement a Google oauth login feature in my application, so I have added the googleapi package from npm. However, I am facing difficulties when trying ...

Transmitting the character symbol '&' within a string from Angular to PHP

My goal is to transmit a string, such as "the cat & the dog", from Angular to PHP using GET method. I have used encodeURI(note) in Angular and in PHP $note = $_GET['note']; $note = mysql_real_escape_string($note); However, when it gets inse ...

Web Browser Fails to Set Cookie during an Ajax Request

I am facing a perplexing issue. I have an AJAX call that triggers the processing of a login form and generates a cookie upon successful login. However, the web browser is failing to recognize the cookie. Upon troubleshooting, I have narrowed it down to so ...

Strategies for effectively engaging with dynamically created forms amidst a multitude of other forms on a webpage

One of the challenges I face is dealing with a page that has multiple forms dynamically generated based on user input. Each form contains two sets of radio buttons, with the second set being disabled by default and enabled based on the users' selectio ...