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

前端 未结 21 2911
既然无缘
既然无缘 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:24

    i have encountered the same error, this thread didn't help... here's my solution it was simple! im using express, mongo, mongoose, and dotENV

    file 1 === db.js

     import mongoose from 'mongoose';
    
    const connectDB =  async ()=>{
    
        try{
            const conn = await mongoose.connect(process.env.MONGO_URI,{
                //must add in order to not get any error masseges:
                useUnifiedTopology:true,
                useNewUrlParser: true,
                useCreateIndex: true
            })
            console.log(`mongo database is connected!!! ${conn.connection.host} `)
        }catch(error){
            console.error(`Error: ${error} `)
            process.exit(1) //passing 1 - will exit the proccess with error
        }
    
    }
    
    export default connectDB
    

    file 2= server.js

    import express from 'express'
    import dotenv from 'dotenv'
    import connectDB from './config/db.js' // DB connection
    import products from './data/products.js'
    
    dotenv.config()
    const PORT = process.env.PORT || 5000
    const mode = process.env.NODE_ENV
    
    const app = express()
    
    connectDB() //this function connects us to the DB!!!
    . . . more code…
    

    > solution: the connectDB() expression must come after the dotenv.config() expression. and that's it ! :)

提交回复
热议问题