I'm encountering an issue in my server.js file where I am unable to read the property 'collection' as it is undefined

I have encountered an error in my code:

/home/ubuntu/workspace/server.js:43
db.collection('quotes').find().toArray(function(err, results) {
  ^
TypeError: Cannot read property 'collection' of undefined
    at Object.<anonymous> (/home/ubuntu/workspace/server.js:43:3)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:139:18)
    at node.js:968:3

Snippet from My Code

const express = require('express');
const bodyParser= require('body-parser')
var MongoClient = require('mongodb').MongoClient
const app = express();
 app.use(bodyParser.urlencoded({extended: true}))

app.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function() {
  console.log("Nodejs Dev Server is Up.");
});

app.get('/',function(req,res){
 res.sendfile(__dirname + '/index.html')
})
var db
MongoClient.connect('mongodb://admin:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d5d0d9dddaf4d0c784858d8c81829ad9d8d5d69atfhvwhlptgjn">[email protected]</a>:19856/star-wars-quote', (err, database) => {
  if (err) return console.log(err)
  db = database
  app.listen(3000, () => {
    console.log('listening on 3000')
  })
})

app.post('/quotes', (req, res) => {
  db.collection('quotes').save(req.body, (err, result) => {
    if (err) return console.log(err)
    console.log('saved to database')
    res.redirect('/')
  })
})

app.get('/', (req, res) => {
  var cursor = db.collection('quotes').find()
})

db.collection('quotes').find().toArray(function(err, results) {
     if (err) return console.log(err)
  console.log(results)
  // send HTML file populated with quotes here
})

Answer №1

Upon reviewing your code, I've identified two issues that need attention: 1) attempting to utilize db.collection before assigning the db variable, and 2) trying to send HTML without properly listening for a request.

Issue #1

The main problem lies in trying to execute db.collection before establishing a connection with the database, resulting in the db variable not being assigned yet.

If the objective is to retrieve quotes when the server initializes, you can resolve this by moving the code inside the MongoClient.connect function callback like this:

MongoClient.connect('mongodb://admin:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5a4a1a8acab85a1b6f5f4fcfdf0f3eba8a9a4a7eba6aaa8">[email protected]</a>:19856/star-wars-quote', (err, database) => {
   if (err) return console.log(err);
   db = database;

   db.collection('quotes').find().toArray(function(err, results) {
      if (err) return console.log(err);
      console.log(results);
   });
});

Issue #2

In the latter part of your code snippet, there's a reference to:

send HTML file populated with quotes here
. However, this is not enclosed within a request callback, which won't function as intended since it requires a request to respond with HTML content (as demonstrated above).

db.collection('quotes').find().toArray(function(err, results) {
    if (err) return console.log(err);
    console.log(results);
    // send HTML file populated with quotes here
});

Recommendation

app.get('/your-quotes-endpoint', (req, res) => {
    db.collection('quotes').find().toArray(function(err, results) {

       // If an error occurs here, consider sending an error response.
       if (err) return console.log(err);
       console.log(results);

       // Generate html
       res.send(/* pass in html string */);
    });
});

Furthermore, note that the root endpoint app.get('/') is defined twice, and app.listen is called twice as well.

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

Modifying paragraph content with JavaScript based on selected radio button values and troubleshooting the onclick event not triggering

I am working on implementing a language selection feature on my website where users can choose between English and Spanish. The idea is to have two radio buttons, one for each language, and a button. When the button is clicked, the text of the paragraphs s ...

Accessing AWS RDS from a Node.js local server

I'm encountering an ETIMEDOUT 172.31.97.43:5432 error when attempting to test my nodejs express app with a postgres database on my local machine connecting to AWS RDS. On AWS RDS, I have configured the necessary settings such as; Configuring Inbound ...

The API successfully completed its operation without issuing a response while attempting to retrieve information from a different page

I've implemented an endpoint that connects to an external database and a page that calls this endpoint within the getServerSideProps function. When I check the API endpoint, it successfully returns data. However, when I navigate to the page, I encount ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

What is the best way to locate the closest element using JavaScript?

Is there a way to locate the closest object to the mouse pointer on a webpage? I have a hypothesis that involves utilizing the array function, however, I am uncertain if that is the correct approach. Furthermore, I lack knowledge of which specific proper ...

Instructions on how to export an HTML table to Excel or PDF by including specific buttons using PHP or JavaScript

I created a table to display leave details of employees with sorting options from date to date. Now, I need to include buttons for exporting the data to Excel and PDF formats. Check out the code below: <form name="filter" method="POST"> <in ...

Problems with Navbar rendering on multiple occasions

GENERAL INFO I've encountered an issue with the re-rendering of my sidemenu in Gatsby. Despite my efforts, I can't prevent the sidemenu from re-rendering and overriding the data that I set for it. const [activeParent, setActiveParent] = useState ...

How can I determine if my clients are utilizing the CDN or NPM versions of my JavaScript library?

At this moment, I'm contemplating releasing an open-source version of my library on NPM. My main concern is figuring out how to track the usage of my CDN or NPM by clients. Is there a method available to achieve this? ...

Failure to pass Express.js data to the view

In my coding project, I have created a route that allows users to access individual database records by their unique ID. On the homepage ('/'), I am displaying all the records but limiting it to show only 10 records per page using the express-pag ...

Ionic ion-view missing title issue

I'm having trouble getting the Ionic title to display on my page: http://codepen.io/hawkphil/pen/oXqgrZ?editors=101 While my code isn't an exact match with the Ionic example, I don't want to complicate things by adding multiple layers of st ...

What are the proper ways to implement JavaScript conditions?

Having an issue with my slider function, as it currently only works once with the moveRight() method. To address this problem, I attempted to implement a condition that disables the move function and modifies the attributes of links on the second click. H ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...

Incorrect outcome when utilizing ajax to update a div within a for each loop

For a while now, I've been facing an issue with a div and form within a forEach loop. When one of the forms in the loop is submitted, the content inside the corresponding div is updated in the database and refreshed using JavaScript and Ajax. The upda ...

How can I trigger a save dialog to allow downloading a file in AngularJS?

On the server, I have a directory containing files. When a client sends a file name, I successfully retrieve the file from the server. The response from the server is working fine so far. However, after receiving the response, I want to prompt the user to ...

Encountered an error when incorporating nguniversal/express-engine into an Angular project: "Unable to locate the BrowserModule import in /src/app/app.module.ts"

One of the initial questions Purpose The main aim is to integrate SSR into my Angular project using ng add @nguniversal/express-engine --clientProject [name] (to enable dynamic prerendering of meta tags). Expected Outcome I anticipated the command to run ...

Tips for assigning a class to a div based on the route in Angular

In my angular template, I have a basic ng-repeat with some div elements. Now, I am looking to add a class to a specific div if the $routeParams.userId matches the id of the object in the loop. You can refer to the second line of code below for clarificatio ...

The D3 data format allows for creating interactive sunburst charts that can be easily zoom

My data is structured similarly to flare.json as shown in this example: I'm curious about the function used by the d3 zoomable chart to format the data in this way. The original structure in flare.json looks like this: { name: "stuff", childr ...

I am looking to customize the color of my Material UI switch

I am having difficulty changing the color of my Material UI switch based on my preference. I have tried several ways, but have not achieved the desired outcome. const useStyles = makeStyles((theme) => ({ toggle: { '& .Mui-checked': ...

Property that is dynamically populated based on data retrieved from an external API

My template relies on an API call (Firebase) to determine the return value of my computed property, which in turn decides whether certain elements are displayed. However, I've noticed that my computed property is not reactive - its value in the templ ...

Removing a pin from google maps using a personalized delete button

I have encountered an issue while attempting to remove a marker from Google Maps using a custom delete button within the info window. Even though I have successfully added the button and necessary information, it seems that the function responsible for del ...