"MongoDB's .find function functions properly in the shell environment, but encounters issues when

As a newcomer to Node Express Mongo, I decided to venture into creating my own website after following tutorials. The page I'm working on is a login page. While other people's code has worked for me, my attempt didn't go as planned. Even consulting the documentation and trying to mimic their examples like db.bios.find( { _id: 5 } ) hasn't helped.

The database I am using is named ShipDB, with a collection called users. The specific document I'm searching for is:

{
        "_id" : ObjectId("56edc18064e429581541808a"),
        "username" : "username",
        "password" : "password"
}

After connecting to the database, when checking result.length for redirection, it always appears as undefined even though I input the correct username and password. Here's what I see in logcat:

Connection established successfully
undefined
{ username: 'username', password: 'password' }



router.post('/validate', function(req, res) {
    var MongoClient = mongodb.MongoClient;
    var url = "mongodb://localhost:27017/"+database_name;
    MongoClient.connect(url, function(err, db) {
       if(!err) {
           console.log("Connection established successfully");
           var user_collection = db.collection(collection_name_users);
           var user_login_input = {
               username: req.body.username,
               password: req.body.password
           };
           // THIS IS THE FUNCTION THAT I HAVE A PROBLEM WITH!!!!
           user_collection.find(
               {
                   username: req.body.username,
                   password: req.body.password
               }, function(err, result) {
                   if(!err) {
                       console.log(result.length);
                       if (result.length) {
                           // Successful login
                           req.session.user = result;
                           delete req.session.user.password;
                           res.redirect("home");
                       } else {
                           console.log(user_login_input);
                           res.send("Invalid login");
                       }

                       db.close();
                   } else {
                       console.log(err);
                   }
           });

       } else {
           console.log("Cannot connect ", err);
       }
    });

});

Attempts made so far include:

  • user_collection.find(user_login_input, function(err, result) {...

  • user_collection.find({ "username": req.body.username, "password": req.body.password })...

  • This works on mongoshell:

https://i.stack.imgur.com/V3KNG.png

Your time and insights are greatly appreciated.

Edit: It seems like findOne might be deprecated based on this feedback:

https://i.stack.imgur.com/pv16d.png

Answer №1

After testing, it appears that node.js produces a similar outcome to the mongo shell. However, the variable result is not recognized as an array and result.length is returning undefined. To resolve this issue, you should first verify whether result is an array or an object.

Upon including the line console.log(user_login_input);, the expected information was successfully displayed as

{ username: 'username', password: 'password' }
.

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

Best practices for implementing JavaScript in JSP pages

After researching various sources, I have come across conflicting opinions on the topic which has left me feeling a bit confused. As someone new to web programming using java EE, I am looking to integrate javascript functions into my code. It appears that ...

Difficulty arises when collapsed text in Bootstrap clashes with the footer design

Hey there! I'm working on this website using Bootstrap, and I've encountered a problem. When you click the "See Wikipedia" button, the content expands and overlaps the footer in a strange way without changing the page height. I've tried adju ...

Combine multiple SCSS files located in various directories into a single CSS file by using NPM

In my project, there are SCSS files stored in a "static" directory. Additionally, I have application components located in a separate directory, each containing its own SCSS file. I am seeking a way to compile all of these SCSS files into a single .css fi ...

Once appearing, the element quickly vanishes after the fadeIn() function is

In the source code, there is a section that looks like this: <div class="dash page" id="home"> <?php include ('pages/home.php'); ?> </div> <div class="dash page" id="screenshots"> <?php include ('pages/scr ...

How do I navigate to a different page in Vue.js HTML based on user selection?

Here is my first attempt at writing HTML code: <div class="col-md-4" > <div class="form-group label-floating"> <label class="control-label">Select No</label> <select class="form-control" v-model="or" required=""> ...

Tips for inserting a php variable into an html document

I am trying to figure out how to export a variable from a php file into an html file. The php file I'm working with is example.php and it contains the following code: <?php $array= ['one','two']; ?> The html file is named ...

Access external variables in next.js outside of its environment configuration

Currently, I am developing my application using next js as the framework. While my environment variables work smoothly within the context of next js, I am facing a challenge when it comes to utilizing them outside of this scope. An option is to use dotenv ...

What are some optimal methods for implementing "multithreading" in a node.js environment?

I have recently been testing the "tiny-worker" module and I've noticed that communication between a worker thread and main thread using postMessage and onmessage can be quite sluggish. Is this slowness typical due to the lack of native multithreading ...

What is the best way to link CSS files from libraries that are downloaded using npm?

For instance, let's say I installed a package: npm install --save package and it gets saved in ./node_modules/package/ Inside that folder, there might be a directory named styles and within that directory, you could find style.css. How can I link ...

Issue: ng-file-upload validation is not functioning correctly, resulting in the form always being considered valid

I'm looking to implement a file-upload feature for each item in an array. In order to achieve this, I am utilizing the ng-repeat directive to cycle through the array and incorporating the ng-file-upload plugin to manage the file upload process along w ...

What is the procedure for inputting the settings for the export module in webpack?

I am currently working on setting up this webpack configuration file. However, I encountered an issue where the error message states that "any" is being used as a value instead of a type. How can I resolve this issue? module.exports:any = { ...

Create a cookie in javascript

There seems to be an issue with this code snippet: function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRc ...

javascript create smooth transitions when navigating between different pages

As a newcomer to JS, I am currently working on creating a website with an introduction animation. My goal is to have this animation displayed on a separate page and once it reaches the end, automatically redirect to the next webpage. <body onload="setT ...

When utilizing AngularJS $resource, it sends an HTTP OPTIONS request in place of the expected HTTP POST when calling the

As I work on developing a basic library application in preparation for a larger AngularJS project, I have been exploring the benefits of using $resource over $http to interact with a RESTful API. While implementing $resource seemed promising for saving tim ...

Is it possible to temporarily halt animation in react-transition-group while retrieving initial data within components?

I am working with the App component that looks like this: <Route render={( { location } ) => ( <TransitionGroup component="div" className="content"> <CSSTransition key={location.key} className ...

Errors and disruptions caused by SmoothScroll, ScrollMagic, and GSAP triggering glitches, jumps, and crashes

Connecting ScrollMagic with GSAP is not an issue - it works seamlessly. However, I encountered a problem when trying to implement smooth scrolling for my mouse. I added a smooth scrolling plugin to my project from this link: http://www.jqueryscript.net/ani ...

Showcase an Array on an HTML page using EJS

When a user posts an object on my website forum using Ejs/NodeJs/MongoDb, it creates a new object with properties like title, comment, and reply array. I have successfully displayed the titles and comments in different HTML elements, but I am facing an i ...

Protractor experiencing timeout issues while trying to launch Chrome Driver on Centos machine

Trying to run the angular-phonecat tutorial on a Centos 6.5 machine with Chrome version 33.0.1750.146, npm 1.4.3, and node version v0.10.31. Attempting to execute protractor tests: npm run protractor Encountering the following error, seeking guidance for ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

Is it recommended to utilize CDN in Vue.js for optimal performance?

Currently facing a version compatibility issue between leaflet and leaflet-draw in my vuejs project. In light of this, I am seeking alternative solutions for map function editing such as adding polylines, copy and paste functions, and more. While I did com ...