Error: The function `mongodb.connect` is not recognized

I encountered some errors in my project using Express.js and despite my attempts to fix them, I couldn't locate the source of the issue.

Below is a snippet of my code:

const mongodb = require("mongodb");
const dotenv = require("dotenv").config();

mongodb.connect(
  process.env.CONNECTION,
  { useNewUrlParser: true, useUnifiedTopology: true },
  function (err, client) {
    if (err) {
      console.log(err);
    } else {
      module.exports = client;
      const app = require("./app");
      app.listen(process.env.PORT, function () {
        console.log("connected");
      });
    }
  }
);

The error message I'm receiving is as follows:

Users/ismailtaibi/Documents/GitHub/worketplace-web/db.js:4 mongodb.connect( ^

TypeError: mongodb.connect is not a function at Object. (/Users/ismailtaibi/Documents/GitHub/worketplace-web/db.js:4:9) at Module._compile (internal/modules/cjs/loader.js:1072:14) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) at Module.load (internal/modules/cjs/loader.js:937:32) at Function.Module._load (internal/modules/cjs/loader.js:778:12) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12) at internal/main/run_main_module.js:17:47

Answer №1

If you're looking for different ways to connect, consider the following options.

const { MongoClient } = require('mongodb');

const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
const client = new MongoClient(uri);
try {
    await client.connect();
    await listDatabases(client);
} catch (e) {
    console.error(e);
}

Alternatively, you can use:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://localhost:27017/mymondb", function (err, db) {
  if(err) throw err;
  console.log('mongodb is running!');
  db.close();
});

Or, opt for the mongoose package:

const express = require('express')
const mongoose = require('mongoose')
const app = express()

mongoose.connect('mongodb://localhost/db1', {
    useNewUrlParser: true, useUnifiedTopology: true
})

app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended:false }))

app.listen(process.env.PORT || 5000);

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

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Issue with npm package mail-listener2: Attachments not being saved for emails received from Outlook 2016

I am attempting to retrieve attachments from Outlook, saving them in a specific folder as outlined in the configuration: { username: "username@here", password: "password", host: "hostName", port: 993, connTimeou ...

Bookmarklet in JavaScript that automatically extracts and displays Meta keywords in a new tab within the browser

I successfully implemented a script that extracts site meta keywords and writes them into the DOM. javascript:(function metaKeywords() { metaCollection = document.getElementsByTagName('meta'); for (i=0;i<metaCollection.length;i++) { nameAttri ...

Step-by-step guide on showcasing a quiz utilizing Magnific-popup and ajax

My goal is to create a functionality that allows users to easily download and view a quiz in a lightbox with just one click. I have successfully set up the ajax features and believe I am using Magnific-popup correctly, but for some reason, the lightbox is ...

What is the best way to determine the total number of rows that have been generated by the Asp:Repeater?

I'm looking for a way to retrieve the total number of rows generated by the repeater control using either Javascript or JQuery. Can anyone help me with this? ...

Hey there, I am interested in deploying a Node webpack bundled application to Heroku

When working with webpack, I noticed that it always bundles the same way on a local environment. I'm not sure if this is normal or not. Here's a snippet of my Heroku log: -----> Node.js app detected -----> Creating runtime environment ...

Determining the Existence of Duplicates in an HTML Table with Multiple Inputs Using JavaScript

After spending countless hours on research with no luck, I've finally come to seek assistance from you. In my form, I have an input field and a select field, along with a table generated using PHP from my database that displays team names and their r ...

designing the structure of directories and routes for express and angular applications

I'm new to using express and angular. After browsing through some answers in the forum, I stumbled upon the express angular seed project. My main question involves the directory structure and routing used in this seed project. In the angular seed ...

Flyer: Move to Web Mercator coordinates (EPSG 3857) using panTo

I am currently using a standard leaflet map with a tile layer. In Leaflet, the only way to use the panTo method is by utilizing LatLng, for example, map.panTo(new L.LatLng(40.17, -98.12)); However, I am wondering how I can use the panTo method if my coor ...

Utilizing AngularJS, combining ng-repeat and filter functions that can be triggered directly from the controller

I have a burning question to ask. Here's the HTML code snippet: ng-repeat="item in obj.Items | filter:someFilter" And here's the JS code snippet: $scope.someFilter = function (item) { ... } It all works perfectly fine. However, I am faced wi ...

When executing JavaScript code with an Ajax HTTP request, the output displayed is 2 but the

I'm currently working on a local chat application and encountering an issue where it displays an undefined result before properly showing all data. Below is the code snippet: function chatDisplay(){ if(mainchat.msg.value== ""){ a ...

JavaScript - Clear the localStorage when closing the final tab of a website

Currently, I am working with AngularJS and utilizing $window.localStorage to store the username of a logged-in user. Since localStorage needs to be explicitly deleted, I have implemented an event listener for $(window).on('unload', function(){}) ...

In order to have the bot repeat a structure for every user, I would need to utilize both mongoose and discord.js

I am utilizing MongoDB (mongoose) to establish a database for storing user notes in my Discord bot, which is being developed with Discord.JS. This is my "Guild.js" file: const { Schema, model } = require('mongoose'); const Guild = Schema({ i ...

Files for the Express API and Sequelize are nowhere to be found

After collaborating with a Freelance developer for more than 10 months on a project, the developer suddenly disappeared without warning. Although he sent me a file containing the work he had completed, I realized that the backend API was missing. Project ...

Angular code is failing to send a signal to the server following a $http.post request

I've been using angular for about a week now and I've been struggling to solve this issue. I have a service that wraps around $http because multiple controllers make calls to the same URL. On one particular page, there is a lot of server-side bus ...

Steps to combine multiple arrays into a unified array:1. Begin by allocating a

To form a league table, I have multiple individual arrays filled with data. In order to sort them by points, I want to merge these arrays into a single array called "teams". However, I am unsure if there is a function available to achieve this specific f ...

Exploring the power of Blowfish encryption with Java and JavaScript

I am facing an issue where I need to encrypt data using Blowfish on a java-based server and send it to a client. Despite successfully encrypting the data, I am unable to decrypt it on the client side. Below is my Java code snippet: byte[] kd = key.getByt ...

Troubleshooting Error in WebSocket with 'ws' Library in Node.js and Vue.js: Issue with RSV1 Flag Unset

I've come across a problem with WebSocket connections while working on my Node.js and Vue.js project. I've implemented the 'ws' library for WebSocket functionality, but I keep getting the error message "Invalid WebSocket frame: RSV1 mus ...

My specific script file in ExpressJS runs and subsequently results in my server encountering a 500 error

var express = require('express'); var router = express.Router(); var root = "resources/"; //where the files will be stored /* GET home page. */ router.get('/', function(req, res) { res.render('index'); }); router.get(&apos ...

Connect select with an array of objects and showcase information when an item is chosen from the dropdown menu

I have an array $scope.items= [ { name: "Jon Snow", email: "jon@example.com", password: "WinterIsComing" }, { name: "Daenerys Targaryen", email: "daenerys@example.com", password: "FireAndBlood" } ]; Now, I am trying to show the email value in a dropdown ...