"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

placeholder for dropdown selection in Vue.js version 2.0.0

Currently, I am in the process of developing a web application using vuejs 2.0. In order to create a straightforward select input, I employed the following code: <select v-model="age"> <option value="" disabled selected hidden>Select Age&l ...

What is the best approach for incorporating sub-navigation within a page popup in a Next.js project?

In the midst of my Next.js project, there is a requirement to showcase a chat popup consisting of multiple sub-pages like user registration, conversation page, and more. Hence, seamless navigation inside this popup is necessary. The idea is not to alter th ...

Issue with Snackbar slide transition not functioning properly in mui 5

Transitioning from material-ui 4 to mui 5 has presented me with a challenge. Whenever I try to display my snackbar, an error pops up in the console. After some investigation, I realized that the issue lies within the Slide component that I'm using as ...

What is the best way to navigate through a webpage to find a specific folder and show its contents on the page?

My goal is to design a webpage where users can browse their computer for a specific folder, select it, and have its content displayed on the webpage. I am fairly new to creating pages, but I want to develop a platform where you can easily find and view f ...

Is React Context suitable for use with containers too?

React provides an explanation for the use of Context feature Context in React allows data sharing that can be seen as "global" within a tree of components, like the authenticated user, theme, or language preference. Although this concept works well for ...

Changing json into another format

I am struggling with a JSON data format issue. I have tried using Object.values and object.keys along with Array.prototype.map(), but my algorithm is not producing the desired outcome. [ { "2018-01-01": [ { "firstname": "mati", "lastname": "mati ...

Having trouble with the setHours function in React not behaving as anticipated?

I'm having trouble adjusting the time in my React application using the setHours method: function App() { let currHour = new Date().setHours(15); return ( <div> <h1>{currHour}</h1> </div> ); } Inst ...

Upgrading from synchronous $.ajax() to AngularJS $http or vanilla JavaScript (XHR) for asynchronous calls

Presented below is a function that I am currently working with: function getDataAvailablity() { var isDataAvailable; $.ajax({ url: 'http://someurl/data.json', async: false, dataType: json }).success(function() ...

Generate a selection of complementary, triadic, and monochromatic color palettes using just one hex color code

My goal is to generate three unique color palettes based on a single hex/rgb value given by the user. The first palette will feature the complementary color of the initial input, followed by a full range of colors in subsequent palettes. I aim to expand be ...

Unable to show message upon form submission with ajax

I'm attempting to use AJAX to submit a form in CodeIgniter. The form values are being saved in the database, but the response set in the controller isn't displaying in the console.log or alert within the AJAX code. Form Code <form class=" ...

Exploring the capabilities of the Jest and Super Test frameworks in Node.js, while utilizing

I'm facing some difficulties while testing the lodash library with jest and supertest A.routes.js import express from 'express'; const router = express.Router(); const _ = require('lodash'); router.post('/', async (req, ...

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

No data being fetched through Ajax

I am facing an issue with retrieving PHP data in the form of an array. I have created an AJAX query to display data in two divs: one is a drop-down and the second is where all data will be shown. However, the problem is that when I attempt to do this, all ...

Experiencing difficulties with Sequelize failing to transmit request parameters to the database

I need help with making a post request to my database using express. When I tried assigning default values, it only posted the default values and ignored the parameters. This is how my database model is structured: const Player = sequelize.define(' ...

Sort firebase information by chronological order based on timestamp

I'm currently working on sorting track IDs from firebase based on their timestamp (createdAt). The function is functioning correctly, but the ordering doesn't seem to work as expected. I'm not sure where the issue lies. Any assistance or sug ...

jQuery UI - Inconsistent results with multiple autocomplete feature

I am facing an issue with the tags.json file provided below: [ {"label" : "Aragorn"}, {"label" : "Arwen"}, {"label" : "Bilbo Baggins"}, {"label" : "Boromir"} ] In addition, I have a JavaScript code snippet (which ...

redirecting the grunt connection to a new URL

Currently, I am utilizing grunt connect with livereload for my development environment. I am looking to access the production API located under /server. In order to achieve this, I need to redirect any requests from http://localhost:9000/server to ...

Utilize moment.js to format a datetime and display the corresponding timezone

I'm having trouble displaying timezones correctly using moment.js. I attempted to use the following code: var result = moment(someDate).format("MM/DD/YYYY HH:mm A Z"); This returns something like: 08/05/2015 06:18 PM +02:00, which is okay, but I w ...

Create a new cookie in Angular if it is not already present

I am looking to check if a cookie is set in Angular. If the cookie is not found, I want to create a new one. Currently, I have this code snippet: if ($cookies.get('storedLCookie').length !== 0) { $cookies.put('storedLCookie',' ...