Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it?

Error: Client is not defined. const db = client.db('products');

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const user = require("./routes/user");
const cors = require('cors');
const MongoClient = require('mongodb').MongoClient;
const mongo_uri = 'mongodb+srv://***:***@cluster0.fetfl.gcp.mongodb.net/*****?retryWrites=true&w=majority';
const db = client.db('products')
const collection = db.collection('brand')

MongoClient.connect(mongo_uri, { useNewUrlParser: true })
.then(client => {
    console.log('connected');
    const db = client.db('products');
    const collection = db.collection('brand');
    app.listen(port, () => console.info(`REST API running on port ${port}`));
}).catch(error => console.error(error));

app.get('/', (req, res) => {
    db.collection('brand').find().toArray().then(results => {
            console.log(results)
        })
        .catch(error => console.error(error))
})

Answer №1

It seems that the variable client is not defined in your code. However, you do have MongoClient defined. Therefore, the correct line of code should be:

const db = MongoClient.db('products')

The variable client itself has not been defined.

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

Interactive Vue components with dynamic children and sub-children

In my Vue application, I have a component called Address.vue which contains a child component called Contact.vue. One address can contain multiple components What I have accomplished: I have implemented the functionality in the Address.vue component t ...

dispatch email display Twitter Bootstrap notification utilizing Ajax

I'm trying to set up an email sending feature via a contact form. I want it to send the email and display a Bootstrap alert confirming that the email has been sent. Below is the HTML code: https://jsfiddle.net/6rfeas35/. Additionally, here is my PHP c ...

What is the method for configuring environment variables in the Lumber framework?

Installing Lumber CLI npm install -g lumber-cli -s Next, lumber generate "adminpanel_test" --connection-url "mysql://root@localhost:3306/admin-dev" --ssl "false" --application-host "localhost" --application-port "3310" Error: lumber is not recognized a ...

What is the best way to handle an AJAX request within an if-else statement?

Attempting to utilize an if-else condition in order to make a jQuery Ajax call to an API. Having trouble understanding why the ajax function is being called even though it should be in the else statement. Below is the code snippet: if (e.value == null | ...

The backend post request is returning only "undefined" in JavaScript

Hey there, I'm still learning JS so please bear with me. I've been working on incrementing a value in a JSON file within my JS backend app. However, whenever I try to increase the associated value by the key, it ends up creating a new section la ...

Sending data from a React application to a Node.js server using Axios

Hello, I am facing an issue with an axios request to post data to a Node.js server. When trying to access this data on the server, it is showing as undefined. Below is the function for posting data: function Submit() { let params={ firstName: ...

Using ASP.NET MVC to transmit JSON information to a Controller method

Even after multiple attempts, I am unable to send JSON data to my ASP.NET MVC3 controller action method successfully. Below is the ajax call I am using (it utilizes the JSON.stringify method from json2.js): $.ajax({ url: '/Home/GetData', ...

Expandable Grid Sections in React MUI

Is there a way to create a grid layout where items with showDefault: true are always displayed at the top, and then users can click an arrow button to expand the grid and also show the items with showDefault: false? Any suggestions on how to achieve this? ...

Checking for undefined values in fields within an array of objects using scenarios in JavaScript

I am encountering an issue with checking for undefined and empty strings in an object array using Javascript. The code provided is partly functional, but I have hit a roadblock. Within the array object, If the field value is undefined or empty, it should ...

What is the best way to target specific text within the DOM without including text within attributes?

We are currently displaying search results from various posts on our website, and we would like to highlight the search terms in the displayed content. Currently, we are implementing this functionality on the backend using PHP. We iterate through the post ...

When the 'keyup' event is detected, trigger the function only on keyup

Looking for assistance in setting this to only trigger on keyup events. Can anyone provide guidance? $(function() { $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() { $('#link-headline-fb').text($( ...

Struggling to connect CSS and JavaScript files to index.html on Heroku while utilizing Node.js

Trying to set up a Tic Tac Toe game in my app.js file, but encountering some issues with linking files in index.html. app.set('port', (process.env.PORT || 5000)) //serve static files in the public directory app.use(express.static('public& ...

What steps do I need to take in order to create functions that are

I have 10 functions with similar structures: function socialMedia_ajax(media){ return ajaxRequest('search/' + media + 'id', media + 'id').then( function(res) { var imgStatus = res[1].length > 0 ? "c ...

Unexpectedly, the API is displaying an empty array despite the fact that there is data

Hi all, as a beginner I am currently working on building a React app with an Express backend. I have successfully created an API that retrieves data from MongoDB. When examining the data in MongoDB using Robo3T, I noticed that the options array appears to ...

Revamp List Model through Ajax Integration in ASP .NET MVC5

Could someone please provide a hint on how to update the Model list in the view page after calling the Action Result with an Ajax request? Specifically, how can I refresh the current list model with the result of the Ajax call back? Here is the code for m ...

The object is given a value in the form of a string, even though it is a strongly-typed variable

I'm encountering something unusual in my code. In the following example, there is a (change) event that captures the current value selected by the user from a dropdown menu. <div style="padding-right: 0; width: 100%;"> <label st ...

Retrieve the element that triggered the event listener within Nuxt

I am currently developing a Nuxt project where I have set up my component using the code below. The select-parent-container has a click event attached to it. Whenever this event is triggered, I need to identify and return the specific parent container that ...

Is the "add" feature malfunctioning?

My code is experiencing an issue where the URL and ID are not being passed correctly from one function to another. When I click on a link that contains the add() function, it fails to capture the URL and ID. <a href="#" style="color:#FFF;" onclick="add ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

Axios transforms into a vow

The console.log outputs of the api and axios variables in the provided code are showing different results, with the state axios becoming a Promise even though no changes were made. The 'api' variable holds the normal axios instance while 'ax ...