บทนำ: mongodb.connect
เมธอด mongodb.connect ใช้เชื่อมต่อเซิร์ฟเวอร์ MongoDB กับแอปพลิเคชัน Node.js เป็นเมธอด asynchronous จากโมดูล MongoDB
ไวยากรณ์
mongodb.connect(path[, callback])
พารามิเตอร์
- path - พาธของเซิร์ฟเวอร์ MongoDB พร้อมพอร์ต (เช่น mongodb://localhost:27017/)
- callback - ฟังก์ชัน callback ที่จะถูกเรียกหากมีข้อผิดพลาด
การติดตั้ง MongoDB Driver
npm install mongodb --save
การรัน MongoDB Server
mongod --dbpath=data --bind_ip 127.0.0.1
ตัวอย่างโค้ดเชื่อมต่อ (MongodbConnect.js)
// Calling the required MongoDB module.
const MongoClient = require("mongodb");
// Server path
const url = 'mongodb://localhost: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... successful connection with the server.