skip to Main Content

i’m new in mongo and i try do make a connection but i receive an error that i don’t kwon how to solve, the error is the below:

MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string. did not connect
(node:21807) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)

my code is the follow:

index.js

    /* MONGOOSE SETUP */
    const PORT = process.env.PORT || 6001;
    mongoose
      .connect(process.env.MONGO_URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      })
      .then(() => {
        app.listen(PORT, () => console.log(`Server Port: ${PORT}`));
      })
      .catch((error) => console.log(`${error} did not connect`));

.env file

MONGO_URL= 'mongodb+srv://User:[email protected]/?retryWrites=true&w=majority'
PORT = 3001

I think that MONGO_URL is not see like a string but i don’t understand why, I have already try to use :

require('dotenv').config();

but in receive this error :

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/gianlca/Desktop/progetto/server/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

i can’t rename it like ‘.cjs’ cause the import that i have in the file they start to not work too

3

Answers


  1. Make sure You have specified Database Name on the URI.

    The URI Should be:

    mongodb+srv://User:[email protected]/yourDataBaseName?retryWrites=true&w=majority
    
    Login or Signup to reply.
  2. In package.json file:

    If you have a line that says "type": "module" change it to "type": "commonjs"

    If you don’t have the line: Add "type:": "commonjs" like shown in the picture

    enter image description here

    Login or Signup to reply.
  3. Your .env file is outside the root directory. If you put it inside the main project folder, it works fine.

    Just tested and confirmed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search