JavaScript and MongoDB issue -- TypeError: Unable to access properties of an undefined value (attempting to read 'collection')

Encountered an error in the terminal or command prompt as discussed below:

The specific error message is:

const taskCollection = db.collection('tasks');
                              ^

TypeError: Cannot read properties of undefined (reading 'collection')
    at Command.<anonymous> (C:\Abc\xyz\Task-Manager-CLI-Project\index.js:50:31)
    at Command.listener [as _actionHandler] (C:\Abc\xyz\Task-Manager-CLI-Project\node_modules\commander\lib\command.js:494:17)
    ...

This pertains to a task manager CLI project linked with mongoDB, yet the persistent error remains unresolved. It's unclear where the issue lies. How can this be rectified? Below are snippets from two code files:

db.js

...
module.exports = {connect, getDB};

index.js

...
program.parse(process.argv);
  1. Attempted altering the URI in MongoDB compass and changed it from "New Connection" to "Project1", updated the URI in db.js. No success.

  2. Switched the URI from mongodb://localhost:27017 to mongodb://localhost:27018 or modified it to mongodb://localhost:27017/Project1. Still facing the same error.

The desired outcome is for commands list, add, delete to operate correctly in the command prompt based on the coded logic. However, the system reports that the collection tasks within database task_manager_db is undefined, leading to property-read errors.

Answer №1

As connect() operates asynchronously, the function should return db within itself and implement await in your index.js script as shown below:

db.js

const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri)

let db;

async function connect(){
    try{
        await client.connect();
        db = client.db('task_manager_db'); 
        return db;
    } catch(err){
        console.log('An error occurred while connecting to the database...', err);
    }
}

module.exports = {connect};

index.js

const program = require('commander');
const {connect} = require('./db');

program
.version('1.0.0')
.description('Task Manager CLI');

program
.command('list')
.description('display a list of commands')
.action(async() => {
    const db = await connect();
    const taskCollection = db.collection('tasks');

    try{
        const tasks = await taskCollection.find().toArray();
        console.log("Listing all tasks:");
        tasks.forEach((task) => {
            console.log(`- ${task.task}`);
        });
   }catch(err){
       console.log("Error displaying tasks...", err);
   }

});

program
.command('add <taskname>')
.description('Include a new task')
.action(async(taskname) => {
    const db = await connect();
    const taskCollection = db.collection('tasks');

    try{
        const result = await taskCollection.insertOne({ task: taskname });
        console.log(`New Task added: ${taskname} TaskID: ${result.insertedId}`);
    }catch(err){
        console.log("Error adding task...", err);
    }
});

program
.command("delete <TaskId>")
.description("Remove a task")
.action(async(TaskId) => {
    const db = await connect();
    const taskCollection = await db.collection('tasks');

    try{
        const result = await taskCollection.deleteOne({ _id: new ObjectId(TaskId) });
        console.log(`Deleted Task (ID: ${TaskId})`);
    }catch(err){
        console.log("An error occurred while deleting a task...", err);
    }
});

program.parse(process.argv);

Answer №2

The problem lies in the connection to MongoDB, which operates asynchronously. To ensure the connection is established before proceeding with any commands, use the async function in your commander action. When dealing with index.js, the snippet for connecting to Mongo should resemble the following:

program
.version('1.0.0')
.description('Task Manager CLI')
//connecting MongoDB database 
.action(async ()=>{
   await connect());
}

This approach guarantees that your connection is fully established prior to executing any actions.

Insights on async actions in commander.js

Understanding why MongoDB shows "Cannot read properties of undefined (reading 'collection')" error

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

Enhance your user interface with an interactive Bootstrap dropdown using Angular

I have a program where users can choose from 3 options such as: Hi, Hello and Hey. Currently, when a user selects one of the values, they receive a message saying that they need to "select a value." I am struggling to figure out how to update the ng-model ...

Switch up a JSON string using JavaScript

I received a JS string through an AJAX API call containing data like this: {"Task":"Hours per Day","Slep":22,"Work":25,"Watch TV":15,"Commute":4,"Eat":7,"Bathroom":17} My goal ...

Implementing a try-catch-finally block in Javascript to handle errors during JSON parsing appears to be ineffective

As someone relatively new to web scripting, I find the similarities between Java try-catch blocks and Javascript ones intriguing. However, my attempts at using them have yielded slightly different results than expected. Here is a snippet of code showcasing ...

Steps for adding a variable to a JSON request

I'm new to JavaScript and React Native and I'm looking for a way to include variables in a JSON request. Specifically, when making a JSON request using Fetch or Axios to a URL, I need to customize the URL based on certain parameters. For instance ...

Creating JOIN tables within the create action involves assigning related ids to each table

I am currently working on a room reservation system that involves including options for each room. Data related to the options and their join table, reservation_options, are successfully inserted into the params. However, I am facing an issue with assignin ...

Monitoring the initiation and completion of web requests within the Ionic framework

Currently utilizing the ionic framework in conjunction with Angular JS. In need of assistance on how to monitor the initiation of a web request. To handle the completion of a request, I have created a directive with an onLoad attribute. Here is the exam ...

An issue occurred while attempting to execute a function in AngularJS

Currently, I am in the process of developing a cross-platform application using AngularJS, Monaca, and Onsen UI. My current challenge involves calling a function in my controller from an ng-click() event on my view. However, upon clicking the button that ...

What is the best way to structure a JSON data string for transmission from a WebView to JavaScript?

Seeking a solution for passing multiple values from an Android WebView to JavaScript. The challenge is that the string received in JS appears completely raw with control characters. The specific issue arises when sending the following string from Java: f ...

Dynamic Filtering of HTML Dropdown Options Based on Another Dropdown Selection

I am facing an issue with multiple HTML dropdowns. My requirement is that upon selecting an option from one dropdown, the next dropdown should get automatically populated. The data to populate these dropdowns is fetched from a database using SQL statements ...

disallow rowOnClick function in the datatable

I am facing an issue with a t:datatable where the rowOnClick event is being triggered. The problem arises when there is an icon in a column that, when clicked, opens a popup. This action also triggers the rowOnClick event, which I don't want. For this ...

is there a way to modify the background color of a div element by comparing values in javascript?

Is there a way to dynamically update the background color of a div element within a table based on values stored in a json array from a database? ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

Is it possible to pass a JavaScript array to a local variable by reference?

Within my namespace, I have an array defined in JavaScript like this: app.collection.box = []; Additionally, there is a function within the same namespace structured as follows: app.init = function () { var box = this.collection.box; // ... code ...

Store the JSON reply as a fixed variable

Recently, I have been delving into ReactJS and I've encountered a challenge of saving a JSON array as a 'const'. I have attempted the following approach: fetch(url) .then(response => response.json()) .then(json => { this.setSt ...

If checkboxes are found within the table's rows and cells, add the parent row class if none of the

I am attempting to implement a small script within my table under the following conditions: The table contains a checkbox within each tr td, and I want my jQuery script to be applied only if the selector identifies a tr where all td checkboxes are unchecke ...

How can I navigate between pages without losing the data entered in the form fields

Is there a way in Ajax or jQuery to save form data and navigate between multiple form pages without using PHP Sessions? I want the form data to be saved until the user submits it, and when they do submit, all information from different pages should be in ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...

What is the best method for utilizing multiple actions and retrieving the total count with MongoDB?

In this query, I am trying to display the count date wise in a chart using MongoDB. The data is stored in an object where multiple actions are separated by the value Action. Currently, only comment count is being displayed, but I also want to show like cou ...

Displaying a value in a React component using material-ui's TextField

Can anyone help me with printing the email a user enters into the textfield within the Dialog when a button is clicked? I have been struggling to achieve this due to my function's structure. Any guidance would be greatly appreciated. export default fu ...

What is the best way to initiate a Bootstrap carousel so that it begins with the first image every time a modal window appears

I am in the process of creating my own portfolio to showcase my work. I have implemented a feature where clicking on an image opens up a Bootstrap carousel. However, I'm facing an issue where the carousel doesn't always start with the first imag ...