mongoose.connect(), first argument should be String, received undefined

前端 未结 21 2914
既然无缘
既然无缘 2021-02-12 15:55

I am trying to set the test database for the testing purpose, but its not working.

I am trying to connect to mongodb using mongoose, but finding problem in connection er

相关标签:
21条回答
  • 2021-02-12 16:31

    If we don't want to define the path of the .env file like this,

    require('dotenv').config({ path: 'ENV_FILENAME' });
    

    we can place .env file in the same place as our main file, which was App.js in my case. So we could directly write

    require('dotenv').config()
    

    0 讨论(0)
  • 2021-02-12 16:31

    In the server directory,

    1. npm install dotenv
      
    2. In your server.js: If you use "type":"module" in your package.json file then,

      import dotenv from 'dotenv';
      import mongoose from 'mongoose'; 
      dotenv.config();
      

      or,

      const mongoose = require('mongoose')
      require('dotenv').config()
      
    3. Add a .env file in the server directory,

      PORT=5000
      MONGO_URL= yourURL
      
    4. In the server.js,

      const url = process.env.MONGO_URL
      mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
      .then(() => app.listen(PORT, () => console.log("Server up and running!")
      .catch((error) => console.log(error.message) 
      mongoose.set('useFindAndModify', false)
      
    0 讨论(0)
  • 2021-02-12 16:32

    To read from .env file you have to install dotenv ( npm i dotenv / yarn add dotenv) and then just add this on top of your file.

    
    const dotenv = require("dotenv");
    
    dotenv.config();
    
    0 讨论(0)
  • 2021-02-12 16:33

    I think you miss importing env file.

    require('dotenv').config({ path: 'ENV_FILENAME' });
    
    0 讨论(0)
  • 2021-02-12 16:37

    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.

    0 讨论(0)
  • 2021-02-12 16:41

    I had same error, for me it was because I was trying to use environment variables in globalSetup which had the file for initiating db connection.. mongoose.connect(global.__MONGO_URI__

    Apparently, environment variables are not initialised yet in globalSetup so I had to move the code somewhere else, either to setupFilesAfterEnv or by using Async Test Environment

    0 讨论(0)
提交回复
热议问题