# 有關連線mongoDB出現的錯誤

在連線的時候若是出現：

```Bash
[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.
```

多半代表的是在關於設定dotenv的部分以及所建立的`.env`的檔案有關有問題

解決的方式大約有：

1. 檢查看code的地方是否有細微的錯誤，像是字串或是引號等。
    
2. 用npm 安裝dotenv以及建立`.env`檔案的順序有關係，若是先建立`.env`檔案後再安裝dotenv，便會出現上述錯誤，因此可以先行試試看順序顛倒。先安裝完在建立`.env`檔
    
3. 安裝完畢後，再檢查code的部分：
    

```javascript
//app.js檔案裡面的code
require("dotenv").config();

mongoose.connect(process.env.MONGO_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});


//.env檔案裡面的code
MONGO_URL = mongodb+srv://<Username>:<Password>@cluster0.2soe8ek.mongodb.net/<Database_Name>?retryWrites=true&w=majority
```

`require()`出現的時間越早越好，而且一定要在`mongoose.connect()`的前面。此外根據這段code還有幾個地方要注意：

* 問題多半發生在`process.env.MONGO_URL`這段，當去`console.log`出來後會發現他是`undefined`，代表他沒抓到`.env`檔案的位置。因此可以設定`.env`檔案的連線位置多加個引號如下，可能可以解決問題(雖然我是一樣會出現錯誤)
    

```javascript
MONGO_URL = "mongodb+srv://<Username>:<Password>@cluster0.2soe8ek.mongodb.net/<Database_Name>?retryWrites=true&w=majority"
```

* 若是無法解決的話則直接使用連線位址，無需使用`process`連線做法，如下：
    

```javascript

require("dotenv").config();

mongoose.connect(MONGO_URL = mongodb+srv://<Username>:<Password>@cluster0.2soe8ek.mongodb.net/<Database_Name>?retryWrites=true&w=majority, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
```

1. .`env`檔案的名稱不能隨便取，最佳就是純粹`.env`這樣
    

解決方式還有其他的，不過簡單的方式大概就是上述這些，可以參考看看。或是直接看[StackOverFlow](https://stackoverflow.com/questions/51770772/mongoose-connect-first-argument-should-be-string-received-undefined)的解法。但是，最佳解答不一定適用，底下很多留言可以用用看(我是看留言的解法才解決的)
