MongoDB and Mongoose - Install and Set Up Mongoose

Tell us what’s happening:

My code isn’t working. I think I’ve written it correctly. My code is saying that “mongoose” should be connected to a database. I’ve tried to rewrite the code a lot of times without getting an error, and I don’t know what’s wrong. Plz help.

require('dotenv').config();
const mongoose = require('mongoose');

// Connect to MongoDB using the URI from the .env file
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('MongoDB connected...');
    // Test the connection by listing databases (optional)
    mongoose.connection.db.admin().listDatabases((err, result) => {
      if (err) {
        console.error('Error listing databases:', err);
      } else {
        console.log('Databases:', result.databases);
      }
    });
  })
  .catch(err => console.log('MongoDB connection error:', err));
{
  "name": "fcc-mongo-mongoose-challenges",
  "version": "0.0.1",
  "description": "A boilerplate project",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "body-parser": "^1.15.2",
    "dotenv": "^8.2.0",
    "express": "^4.12.4",
    "mongodb": "MONGO_URI",
    "mongoose": "^5.11.15"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/freeCodeCamp/boilerplate-mongomongoose.git"
  },
  "keywords": [
    "node",
    "mongoose",
    "express"
  ],
  "license": "MIT"
}
GLITCH_DEBUGGER=true
SECRET=
MADE_WITH=
MONGO_URI="mongodb+srv://xxxx:###@****.mongodb.net/"

###Your project link(s)

solution: https://3000-freecodecam-boilerplate-dhkfnfi4hdo.ws-us117.gitpod.io

Your browser information:

User Agent is: Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36

Challenge Information:

MongoDB and Mongoose - Install and Set Up Mongoose

Hi @juicethekidd

Try removing the then and catch

Also, please remove your email and password from the post.
This is a public forum and anyone on the internet can view it.

Happy coding

The edit button isn’t there. I did remove the then and catch, but now it shows this error:
MongoParseError: URI contained empty userinfo section

I masked the code for you.

Thank you about that.

Try adding

?retryWrites=true&w=majority&appName=Cluster0

at the end of the MONGO_URI in the .env file
(between forward slash and the last quote mark)

shows this error:
MongoServerError: bad auth : authentication failed
could it be because of this:
(node:755) [DEP0040] DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead.

Hi @juicethekidd

Ignore the message and click on the I’ve completed this challenge button.

However, the bad auth is troubling.

Try your code without adding the ? string to the end of the MONGO_URI variable.

Happy coding

I did what you said, but it kicks me out with the error:
Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"
even though I have monogodb and mongodb+srv://

Use this a a template for the MONGO_URI variable:

MONGO_URI="mongodb+srv://<db_username>:<db_password>@cluster0.<website>"

For the cluster number, it will depend on what you used on the mongodb website.

It still kicks me out, with this error,
MongoParseError: mongodb+srv URI cannot have port number
and this warning is still here,
DeprecationWarning: The punycode module is deprecated. Please use a userland alternative instead.

Remove these variables from the .env file:

still kicks me out, with this error:
MongoParseError: mongodb+srv URI cannot have port number
is the warning important?

There maybe special characters in the password causing it to be read as a port number.

Can you try resetting the password?

Good morning afternoon @Teller. How do I do that?

On the Mongodb website, under Security select Database Access
On the line with your email address, under Actions, click EDIT

Under Authentication Method select Password

Under Password Authentication click Edit Password, then click Autogenerate Secure Password
Click the Copy button next to the previous button to copy the password.
Store it in a safe place.

Also under Security check in Network Access that your ip address is listed, and the status is active

Under Database click Clusters
Click on the Connect button.
Under Connect to your application select Drivers
Under 3. Add your connection string into your application code click the copy button on the far right (the icon looks like two pages).
Replace <db_password> with the password from earlier.

Paste that mongo+srv string into the .env file as the value for the MONGO_URI variable.

Happy coding

Good morning, @Teller. I did what you said(and added the username also because you didn’t say what to do with it) and then I get this error:
MongoServerError: bad auth : Authentication failed.
I double checked to see if I did everything right, and I did.
What else should I do?

Near the top right of the MongoDb page there is an account icon.
Click on it then go to their forum using the link.

First search for the error message keywords to see if there are similar posts, and any solutions or advice provided. Or make a new post, giving as many details as possible, such as a description of the problem, and the error messages you received. Do not include your username or password.

Post the URI string:

mongodb+srv://<db_username>:<db_password>@cluster0.<website>

replacing sensitive information with angular brackets and text descriptions of what you removed.

Happy coding

@juicethekidd maybe if you can post what you are doing with this line, but with fake data that simulates your confidential data?

mongodb+srv://<db_username>:<db_password>@cluster0.

We would like to see what you are writing, to verify it is the right setting?

And the same with any confidential data - give us an example always modifying confidential values with fake but similar ones to the ones you are using.

(The security level of the database configurations is usually very very picky and strict for all databases. It takes time to learn where the error is coming from. We all have been there… :roll_eyes:)