ข้อมูลเบื้องต้นเกี่ยวกับ mongodb.connect
วิธีนี้ใช้เพื่อเชื่อมต่อเซิร์ฟเวอร์ Mongo DB กับแอปพลิเคชัน Node ของเรา นี่เป็นวิธีการแบบอะซิงโครนัสจากโมดูล MongoDB
ไวยากรณ์
mongodb.connect(path[, callback])
พารามิเตอร์
-
•เส้นทาง – เส้นทางเซิร์ฟเวอร์ที่เซิร์ฟเวอร์ MongoDB ทำงานจริงพร้อมกับพอร์ต
-
•โทรกลับ – ฟังก์ชันนี้จะโทรกลับหากมีข้อผิดพลาดเกิดขึ้น
การติดตั้ง Mongo-DB
ก่อนดำเนินการต่อเพื่อลองเชื่อมต่อแอปพลิเคชันของคุณกับ Nodejs เราจำเป็นต้องตั้งค่าเซิร์ฟเวอร์ MongoDB ของเราก่อน
-
ใช้แบบสอบถามต่อไปนี้เพื่อติดตั้ง mongoDB จาก npm
npm install mongodb –save
-
รันคำสั่งต่อไปนี้เพื่อตั้งค่า mongoDB ของคุณบนเซิร์ฟเวอร์ localhost ที่ระบุ ซึ่งจะช่วยในการสร้างการเชื่อมต่อกับ 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://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, 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.