Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Kết nối MongoDB với Node.js (MongoClient.connect)

Phương thức mongodb.connect

Phương thức bất đồng bộ MongoClient.connect() dùng để kết nối Node.js application với MongoDB server.

Cú pháp

MongoClient.connect(url[, options], callback)

Tham số

  • url: Chuỗi kết nối, ví dụ mongodb://localhost:27017/
  • callback: Hàm callback nhận (err, client)

Cài đặt MongoDB driver

npm install mongodb --save

Khởi động MongoDB server (nếu cần)

mongod --dbpath=data --bind_ip 127.0.0.1

Ví dụ kết nối cơ bản

File: MongodbConnect.js

const MongoClient = require("mongodb");
const url = 'mongodb://localhost:27017/';
const dbname = "Employee";

MongoClient.connect(url, (err, client) => {
  if (!err) {
    console.log("successful connection with the server");
    // client.db(dbname) để thao tác database
  } else {
    console.log("Error in the connectivity");
  }
});

Chạy

node MongodbConnect.js

Kết quả mong đợi

successful connection with the server

Lưu ý: Phiên bản driver mới khuyến khích dùng useUnifiedTopology: true trong options để tránh cảnh báo deprecation.