Error: The function client.db is not recognized in MongoDB Atlas

I am attempting to establish a connection to MongoDB Atlas in Node.js using the client "mongodb": "^3.5.5" by following the instructions provided in this particular guide. A successful connection message of console.log('connected to db') is displayed, but upon trying to execute find(), I encounter the error message client.db is not a function.

const { MongoClient } = require('mongodb');
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config();

// Establish MongoDB Connection
 const connectClient = async() => {
  const client = new MongoClient(process.env.MONGODB_CONNECTION_URI);
  try {
      await client.connect();
      console.log('connected to db')
      return client;
  } catch (e) {
      console.error(e);
  } finally {
      await client.close();
  }
}
const client = connectClient();

const find = async() => {
  try {
    const cursor = client.db('meetings').collection('inperson').find();
    const results = await cursor.toArray();
    return results
  } catch (err) {
    console.log(err)
  }
}

app.use(cors());

app.get("/get-meetings", (req, res) => {
  const results = find();
  res.status(200).send({ results });
});

app.listen(8081, () => console.log("Server running on 8081"));

The format of the connection URI is as follows:

mongodb+srv://meetingsAPI:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f7f2a0afeed9f0f9e0c5eed7c7f7d2a3d6fbf3f3e2fff8f1e5bbf1f8e2f9e4b8f1f5e6b8fbf9f8f1f9f2f4b8f8f3e2">[email protected]</a>/meetings?retryWrites=true&w=majority

Answer №1

The function connectClient is designed to return a promise as it is an async function. When you call it like this:

const client = connectClient();

The variable "client" actually refers to the promise itself and not the resolved value, which is why the .db property is inaccessible. To ensure that the await keyword functions correctly, wrap your code in an immediately invoked function expression like so:

//Make sure any code before this ends with semicolon
(async() => {
    //code...
    const client = await connectClient();
    //code...
    app.listen(8081, () => console.log("Server running on 8081"));

})()

While there are other ways to handle this situation, I find this approach to be the most effective. For more insights, you can refer to this resource: https://dev.to/codeprototype/async-without-await-await-without-async--oom

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

The error encountered is an unhandled rejection with a message stating "TypeError: Cannot access property 'username' of null

My tech stack includes NodeJS, PassportJS, MySQL, and Sequelize (ORM for MySQL). The following code snippet is taken from my Passport.JS file. Whenever a user registers on my website, an error is returned if the username or email is already in use. If both ...

Is it beneficial to dockerize an AngularJS + nginx codebase?

Currently, I am working on an AngularJS front-end project that is hosted on nginx and communicates with a back-end Java server (which is not part of this codebase). Each time I need to install the package, I run the following commands: # ensure that node, ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

Server connection failure: MongoDB is unable to establish a connection

UPDATE: After attempting different ports, terminating tasks on ports, and trying again, I am still unable to connect. Today, I embarked on a tutorial for the MERN stack but unfortunately, I am unable to establish a connection to the server. Upon using npm ...

What is the process for updating an item in Sequelize?

Seeking help with updating an object in Sequelize. Here is the code I'm using: const updateEmployee = async (req, res) =>{ let {full_name, email, phone_number, address} = req.body const id = req.params.id; Employee.findOne({ wh ...

Gulp command could not be found in the specified directory: /usr/local/bin/gulp

Every time I try to run gulp, I keep encountering this error message: /usr/local/bin/gulp: No such file or directory Despite following advice from various questions on SO, none of the solutions have resolved my issue. I've been using gulp smoot ...

Is there a way to retrieve all active HTTP connections on my Express.js server?

In my express server app, I am implementing SSE (server send events) to inform clients about certain events. Below is the code snippet from my server: sseRouter.get("/stream", (req, res) => { sse.init(req, res); }); let streamCount = 0; class SS ...

Leverage the power of combining Shouldjs and Bluebird for comprehensive Promise testing

Is it possible to test Promises using Shouldjs with Bluebird? var should = require('should'); var Promise = require('bluebird'); Promise.reject().should.be.fulfilled(); > TypeError: Promise.reject(...).should.be.fulfilled is not a f ...

Struggling with Sequelize.js setter functions not functioning as expected

I encountered a challenge with my sequelize.js test script. The code snippet below showcases what I have implemented: department.hasMany(employee,{as:'employees', foreignKey:'DepartamentoID'}); let prog = department.build({nombre:&apo ...

An issue was encountered with initializing digital envelope routines on a Vue.Js Project, error code 03000086

I'm encountering an issue with my Vue Project when I try to execute "npm run serve/build" syntax in the terminal. My npm node version is currently v18.12.0 (with npm 8.19.2) The error message being displayed is: opensslErrorStack: [ 'error:03 ...

The proper way to retrieve data using getServerSideProps

Encountering an issue with Next.js: Upon reaching pages/users, the following error is displayed: ./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0 Module not found: Can't resolve 'dns' Import trace for requested module: ./node_modules/mon ...

Guide on incorporating jQuery library files into existing application code with the npm command

Recently, I used a node JS yo ko command to create a single-page application using Knockout-JS. Following that, I proceeded to install jquery packages using the command npm install jquery The installation was successful. However, my current goal is to in ...

Can someone help me figure out how to simulate an express middleware class method using jest and supertest?

I'm facing some challenges trying to achieve the desired outcome when mocking a method in a class using jest and supertest. I'm specifically looking for a solution that can help me bypass the verifyAuthenticated method with a mocked version in or ...

Express always correlates the HTTP path with the most recently configured route

Recently, I encountered a strange issue with my Express routes configuration. It seems that no matter which path I request from the server, only the callback for the "/admin" route is being invoked. To shed some light on how routes are set up in my main N ...

Best practices for securing your App/API endpoints

I am currently in the process of developing a mobile app (using Ionic/Cordova) that will interact with an API built with NodeJS. As I navigate through this project, I find myself contemplating how to implement a user authentication method that serves dual ...

Retrieving data from MongoDB and saving it to your computer's hard drive

I've asked a variety of questions and received only limited answers, but it has brought me this far: Mongoose code : app.get('/Download/:file(*)', function (req, res) { grid.mongo = mongoose.mongo; var gfs = grid(conn.db); var fi ...

Encountering a problem with library functions while attempting to import a module

At the moment, I am utilizing NodeJS. I have been attempting to import a module into a component function and everything appears to be running smoothly. However, I keep encountering this error in the server console: error - src\modules\accountFu ...

Should I use express with NodeJS and socket.io?

Just a quick question. I'm currently in the process of creating an online browser game with phaser and socket.io. I know I'll be using socket.io quite a bit, but what about express? Once I start the server, what other tasks will I need to complet ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

What are the steps to set up the node mysql module in nw.js?

Currently, I am in the process of developing a desktop application using NW.JS. My goal is to store data in a MySQL database, but I have encountered an issue when trying to add the MySQL node module to my nw.js application. As a beginner, I would greatly ...