What is the process for linking my MongoDB database to my laptop?

I recently created a MongoDB account and attempted to connect it to my laptop, but unfortunately I encountered an error during the process.

Below is the code snippet for my Mongoose connection:

mongoose.connect(
  'mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}@cluster0.atfhj.mongodb.net/${process.env.MONGO_DB_DATABASE}?authSource=yourDB&w=1',
    {
        useUnifiedTopology: true,
        useNewUrlParser: true
    }).then(() => {
        console.log("database connected");
    }).catch((err) => console.log(err));
app.use(bodyParser)

Upon connecting, I encountered the following error message:

server started on port 5000
MongoError: Authentication failed.
at MessageStream.messageHandler (C:\Users\JUWONCALEB.DESKTOP-CMA289U\Desktop\UDEMY\ECOMMERCE\backend\node_modules\mongodb\lib\cmap\connection.js:268:20)
at MessageStream.emit (events.js:314:20)
at processIncomingData (C:\Users\JUWONCALEB.DESKTOP-CMA289U\Desktop\UDEMY\ECOMMERCE\backend\node_modules\mongodb\lib\cmap\message_stream.js:144:12)
at MessageStream._write (C:\Users\JUWONCALEB.DESKTOP-CMA289U\Desktop\UDEMY\ECOMMERCE\backend\node_modules\mongodb\lib\cmap\message_stream.js:42:5)
at doWrite (_stream_writable.js:403:12)
at writeOrBuffer (_stream_writable.js:387:5)
at MessageStream.Writable.write (_stream_writable.js:318:11)
at TLSSocket.ondata (_stream_readable.js:719:22)
at TLSSocket.emit (events.js:314:20)
at addChunk (_stream_readable.js:298:12)
at readableAddChunk (_stream_readable.js:273:9)
at TLSSocket.Readable.push (_stream_readable.js:214:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:188:23) {
ok: 0,
  code: 8000,
  codeName: 'AtlasError'
}

Answer №1

Make sure to enclose string interpolations with Backticks.

mongoose.connect(
  `mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}@cluster0.atfhj.mongodb.net/${process.env.MONGO_DB_DATABASE}?authSource=yourDB&w=1`,
    {
        useUnifiedTopology: true,
        useNewUrlParser: true
    }).then(() => {
        console.log("connected to database");
    }).catch((err) => console.log(err));
app.use(bodyParser)

Answer №2

It appears that you are using single quotes '' instead of backticks ``. This may have been the cause of the error you encountered. Another possibility is that your environment configuration could be incorrect. Verify if your environment is functioning properly by logging it to the console.

I recommend setting up the entire MongoDB Connection as an environment variable and accessing it without needing to worry about strings.

For example, in your .env file:

DATABASE_CONNECTION=mongodb+srv://the-user:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffafceafda2ffeefcfcf8e0fdebcfece3fafcfbeafdbfa1eefbe9e7e5a1e2e0e1e8e0bcedbef">[email protected]</a>/your-database?authSource=yourDB&w=1

Then you can simply do this:

mongoose.connect(
  process.env.DATABASE_CONNECTION,
    {
        useUnifiedTopology: true,
        useNewUrlParser: true
    }).then(() => {
        console.log("database connected");
    }).catch((err) => console.log(err));
app.use(bodyParser)

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

Generate a new nested div if there is already a different child present at the specified coordinates (x, y)

My goal is to add a textarea to a sidebar on the right whenever a click is made on the page. The current code I have is as follows: $('#page_to_be_clicked').click(function(e){ var offset = $(this).offset(); var comment_box_y_coord = e.pa ...

Creating Personalized Checkboxes for Internet Explorer Versions 7 and 8

I am currently in the process of implementing custom checkboxes for my website. Everything is functioning smoothly on browsers such as IE9 and other modern ones. However, I am encountering issues with IE8 and 7. Below is a snippet of my CSS code: input[typ ...

Filtering in AngularJS seems to only work in one direction

I am working on implementing two different ways of filtering data - one by clicking on letters and the other by typing in an input field. <body ng-controller="MainController"> <ul search-list=".letter" model="search"> <li class= ...

What is the best way to calculate the pixel height of an element when the height is specified in vh units?

element lies this inquiry: In my JavaScript code for developing Windows 8 apps, I have set the max-height of an element to 65vh. I now require a method to convert this value into pixels in order to determine if an image can adequately fit within this spac ...

Querying MongoDB for results grouped by count

db.tickets.aggregate([ {$project: {_id: 0, daysSince: {$divide: [{ $subtract: [ 2020, {$convert:{input:{$substrCP:["$data.DATE_BIRTH", 6, 4]}, to: "int"}}]}, 45]}}}, ...

Improving the efficiency of your if else code in React js

I am looking for a way to optimize my code using a switch statement instead of multiple if-else conditions. How can I achieve this? Here is the current version of my code: handleChange = (selectedkey) => { this.setState({ activeKey: selectedkey } ...

Merging gulp-sourcemaps with gulp-csso and gulp-sass for optimized workflow

I'm currently troubleshooting a section of my gulpfile.js: gulp.task('compileSass', function() { return gulp.src(folders.src+'/scss/*scss') .pipe(sass()) .pipe(gulp.dest(folders.dest+'/css')); }); gulp.task( ...

Unable to access a JavaScript array in one file from another file in JavaScript

I am having trouble referencing the arrays I created in a.js and then using them in b.js. The arrays are declared inside a.js $(document).ready(function () { categoryarray = []; productarray = []; In my HTML file, I have the following script tags: < ...

What is the best method for choosing a document from a Firebase based on its creation time?

Currently delving into Firebase as part of my project, struggling with setting queries in the Database. I've provided a breakdown of my Firebase database structure below: Looking to retrieve the most recently created document from the 'subscrip ...

Search for data in MongoDB that falls outside of a specific range and is not between the

When attempting to query data outside of an integer range, I am encountering some challenges. So far, I have been able to successfully query a "between" range using the following code: { '$where': "#{some_method(field)} <= #{value[1]} && ...

The references to the differential loading script in index.html vary between running ng serve versus ng build

After the upgrade to Angular 8, I encountered a problem where ng build was generating an index.html file that supported differential loading. However, when using ng serve, it produced a different index.html with references to only some 'es5' scri ...

javascript function returns an array

My behaviors are not returning properly function listBehaviors() { var behaviors = getBehaviors(); console.log("Creating behavior list"); console.log(behaviors); $.each(behaviors, function (index, value) { if (value.indexO ...

Managing plain text response in AngularJS

I have a requirement to display the response in text/plain format from a POST API on the GUI. Below is my code for performing an HTTP post operation: $http.post("/compare").success(function(data){ cb(data); }).error(function(error){ ...

synchronously retrieve the result of an asynchronous function

In my current project, I am developing a custom render function for marked. This function is responsible for checking specific conditions on images, performing an asynchronous request, and ultimately returning an image from a different source. The challeng ...

Arrange the array first by a specific data type and then by the intended sorting sequence

I am trying to manipulate an array and move specific elements to the beginning while sorting the remaining elements in alphanumeric order. Here is an example of my initial array: const array1 = ['x123', 'y123', 'z123', 'a ...

Confirming the information before submitting the form

My submit button is set up like this: <input class="create_button" name="commit" onclick="return validate_activity();" type="submit" value="Save"> I have noticed that this button always sends a request to the server regardless of wh ...

The error in Node.js doesn't seem to be visible when checking through the command line

I'm facing a challenge in creating an HTTP server with GET and POST requests using Node.js. The goal is to allow users to upload images and files, but I'm encountering an issue where the command line in Node.js isn't displaying the actual er ...

Encountered a problem when injecting the angularjs $location service

I'm having some trouble getting the $location service to work in this code snippet: <script type="text/javascript> var $injector = angular.injector(['ng', 'kinvey', 'app.constants']); $in ...

What's the best way to handle variables and numerical calculations within PHP loops when dealing with forms?

I'm currently developing a basic PHP page where users can choose how many numbers they want to add together. After selecting the quantity, they input the numbers on a new page, click a button, and then see the sum displayed. The challenge I'm fa ...

Retrieve the JSON data from the server's response

{"identifier":"2231f87c-a62c-4c2c-8f5d-b76d11942301"} After alerting the response data, I discovered the code snippet shown above. Now, how can I retrieve the value of the identifier? The controller is set up to return like this: return Json( new { ...