การเชื่อมต่อและการสืบค้น MongoDB ใน Express

ในกระบวนการพัฒนาเว็บแอปพลิเคชัน การเชื่อมต่อและสอบถามฐานข้อมูลเป็นส่วนสำคัญ ในบทความนี้ เราจะสำรวจวิธีเชื่อมต่อและสอบถามฐานข้อมูล MongoDB ในแอปพลิเคชัน Express MongoDB เป็นตัวเลือกยอดนิยมสำหรับการจัดเก็บข้อมูลในแอปพลิเคชัน Node.js เนื่องจากมีความยืดหยุ่นและปรับขนาดได้

 

การเชื่อมต่อ MongoDB กับ Express:

ในการเริ่มต้น เราจำเป็นต้องติดตั้งแพ็คเกจ Mongoose ผ่าน npm และกำหนดค่าการเชื่อมต่อกับฐานข้อมูล MongoDB

npm install express mongoose

ตัวอย่างการเชื่อมต่อ MongoDB กับ Express:

const mongoose = require('mongoose');
const express = require('express');
const app = express();

// Connect to the MongoDB database
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to MongoDB');
    // Continue writing routes and logic in Express
  })
  .catch((error) => {
    console.error('Error connecting to MongoDB:', error);
  });

// ... Other routes and logic in Express

app.listen(3000, () => {
  console.log('Server started');
});

 

การสืบค้นข้อมูลจาก MongoDB:

หลังจากเชื่อมต่อกับ MongoDB สำเร็จ เราสามารถทำการสืบค้นข้อมูลภายในแอปพลิเคชัน Express ได้ ต่อไปนี้เป็นตัวอย่างของการสืบค้นข้อมูลจาก MongoDB โดยใช้ Mongoose:

const mongoose = require('mongoose');

// Define the schema and model
const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

const User = mongoose.model('User', userSchema);

// Query data from MongoDB
User.find({ age: { $gte: 18 } })
  .then((users) => {
    console.log('List of users:', users);
    // Continue processing the returned data
  })
  .catch((error) => {
    console.error('Error querying data:', error);
  });

ในตัวอย่างข้างต้น เรากำหนดสคีมาสำหรับอ็อบเจ็กต์ "ผู้ใช้" และใช้โมเดลเพื่อดำเนินการสืบค้นข้อมูล ที่นี่ เราค้นหาผู้ใช้ทั้งหมดที่มีอายุมากกว่าหรือเท่ากับ 18 ปี และบันทึกผลลัพธ์ที่ส่งคืน

 

สรุป:ในบทความนี้ เราได้สำรวจวิธีเชื่อมต่อและสอบถามฐานข้อมูล MongoDB ในแอปพลิเคชัน Express การใช้ MongoDB เป็นโซลูชันฐานข้อมูลสำหรับแอปพลิเคชัน Node.js ทำให้เรามีตัวเลือกที่ยืดหยุ่นและมีประสิทธิภาพ ด้วยการใช้ Mongoose เราสามารถทำการสืบค้นข้อมูลและสร้างเว็บแอปพลิเคชันที่เชื่อถือได้ได้อย่างง่ายดาย