透過 NodeJS 連線 MongoDB


mongodb.connect 簡介

此方法用於將 Mongo DB 伺服器與 Node 應用程式連線起來。這是 MongoDB 模組中的一種非同步方法。

語法

mongodb.connect(path[, callback])

引數

  • •path – MongoDB 伺服器實際執行的伺服器路徑及其埠。

  • •callback – 如果發生任何錯誤,此函式將提供回撥。

安裝 Mongo-DB

在嘗試使用 Nodejs 連線應用程式之前,我們需要首先設定 MongoDB 伺服器。

  • 使用以下查詢從 npm 安裝 mongoDB。

npm install mongodb –save
  • 執行以下命令在特定本地伺服器上設定 mongoDB。這將有助於建立與 MongoDB 的連線。

mongod --dbpath=data --bind_ip 127.0.0.1
  • 建立一個 MongodbConnect.js 並將以下程式碼片段複製貼上到該檔案中。

  • 現在,執行以下命令來執行程式碼片段。

node MongodbConnect.js

示例

// Calling the required MongoDB module.
const MongoClient = require("mongodb");

// Server path
const url = 'mongodb://:27017/';

// Name of the database
const dbname = "Employee";

MongoClient.connect(url, (err,client)=>{
   if(!err) {
      console.log("successful connection with the server");
   }
   else
      console.log("Error in the connectivity");
})

輸出

C:\Users\tutorialsPoint\> node MongodbConnect.js
(node:7016) 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.
(Use `node --trace-deprecation ...` to show where the warning was created)
successful connection with the server.

更新時間: 2021-4-27

1K+ 瀏覽量

啟動您的職業生涯

完成課程以取得認證

開始
廣告