[Node.js] 學習筆記-連接MongoDB (2)

前言

這是一個Node.js + Vue.js 使用MongoDB的學習筆記。

並不會有詳細的教學,因為這是筆記!!

需要對node.js和vue.js有基礎的認識才適合觀看。

學習資源:https://www.udemy.com/share/102an4AkUddV1XRnw=/

事前準備

  • 註冊一個mogoDB帳號並且創建一個project,拿到Connection String Only。

    ex : mongodb+srv://<userName>:<password>@XXXXXXXXXXXXX

安裝及連接Mongoose

終端機:

> npm install mongoose

引入及配置Mongoose

server.js :

const mongoose = require("mongoose");
mongoose.connect(
  "mongodb+srv://<userName>:<password>@XXXXXXXXXXXXX")
    .then(() => console.log('MongoDB Connected')) //成功時顯示MongoDB Connected
    .catch(err => console.log(err)); 

服務啟動的提醒處理

終端機:

//儲存後服務自動重啟
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
(node:1791) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
Server running on port 5000
(node:1791) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoDB Connected

正常連上MongoDB Connected,但是出現{ useNewUrlParser: true }和{ useUnifiedTopology: true }的提醒,所以我們將它複製貼到server.js裡。

server.js :

const mongoose = require("mongoose");
mongoose.connect(
  "mongodb+srv://<userName>:<password>@XXXXXXXXXXXXX",
  { useNewUrlParser: true , useUnifiedTopology: true})
    .then(() => console.log('MongoDB Connected')) //成功時顯示MongoDB Connected
    .catch(err => console.log(err)); 

儲存後就會發現提醒不會出現了。

終端機:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server running on port 5000
MongoDB Connected 

將Connection String移出

創建一個文件夾config裡面新增一個keys.js。

keys.js:

//使用module.exports讓它能夠正確引入
module.exports={
    mongoURI : 
        "mongodb+srv://<userName>:<password>@XXXXXXXXXXXXX"
}; 

接著引入到server.js

server.js :

const db = require("./config/keys").mongoURI; //引入connection string

mongoose.connect(db,{ useNewUrlParser: true , useUnifiedTopology: true})
    .then(() => console.log('MongoDB Connected'))
    .catch(err => console.log(err));

這樣修改對應的連接字串時到keys做修改即可。

嘗試DB錯誤訊息

將用戶名或密碼改成錯誤的儲存。

終端機:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server running on port 5000
{ MongoTimeoutError: Server selection timed out after 30000 ms
    at Timeout.setTimeout [as _onTimeout] (/Users/siaoyuu/Desktop/project/node-demo/node-app/node_modules/mongodb/lib/core/sdam/server_selection.js:308:9)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)
  name: 'MongoTimeoutError',
  reason:
   { MongoError: bad auth Authentication failed. //這裡會顯示權限錯誤
     ---省略---
     name: 'MongoNetworkError',
     [Symbol(mongoErrorContextSymbol)]: {} },
  [Symbol(mongoErrorContextSymbol)]: {} }