DEV Community

Bhurisub Dejpipatpracha
Bhurisub Dejpipatpracha

Posted on • Edited on

4

Node.js : การเขียนสคริปต์ติดต่อฐานข้อมูล Mongo

บทความนี้จะแนะนำการเขียนสคริปต์ JavaScript ติดต่อกับฐานข้อมูล Mongo ซึ่งจะต้องอาศัยมอดูลในการติดต่อฐานข้อมูล Mongo ในตัวอย่างที่นี่ขอแนะนำมอดูลชื่อ mongodb ซึ่งมีชื่อเดียวกันกับฐานข้อมูลเลย

เริ่มจากติดตั้งมอดูล mongodb
npm i mongodb หรือ npm install mongodb

การติดต่อฐานข้อมูล Mongo

const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017'
const option= { useNewUrlParser: true,useUnifiedTopology: true }
const dbName = 'webphuket'

MongoClient.connect(url,option,(err, client) => {
  if (err) throw err

  const mongo = client.db(dbName)
  console.log("Connected successfully to server")
  client.close()
})

กำหนดตัวแปร MongoClient เพื่อเรียกใช้มอดูล mongodb
กำหนดตัวแปร url เพื่อกำหนด URLและ port เพื่อติดต่อฐานข้อมูล Mongo
กำหนดตัวแปร dbName เพื่อกำหนดชื่อฐานข้อมูล

จากนั้นติดต่อฐานข้อมูล Mongo ด้วย method ชื่อ connect()

การเพิ่มข้อมูล

...
...
  var data = { 
    title : 'Product 1',
    price : 1000
  }
  mongo.collection('products').insertOne(data, (err, r) => {
    console.log('documents inserted  : ',r.insertedCount) 
    client.close()
  })

สำหรับการเพิ่มข้อมูลต้องกำหนดข้อมูลเก็บไว้ในตัวแปร data ขอยกตัวอย่างข้อมูลดังนี้ หัวข้อ title ชื่อสินค้า Product 1 และราคาสินค้า price เท่ากับ 1000 เป็นต้น

จากกำหนด Collection ที่ต้องการเพิ่มในตัวอย่างชื่อ products และใช้ method ชื่อ insertOne() เป็นการเพิ่มข้อมูลชุดเดียวกัน

และในกรณีต้องการเพิ่มข้อมูลหลายๆ ชุดในครั้งเดียว ก็สามารถใช้ method ชื่อ insertMany() ได้ดังตัวอย่าง

การเพิ่มข้อมูลหลายๆ ชุดในครั้งเดียว

...
...
  var data = [
    { title : 'Product 2', price : 2000},
    { title : 'Product 3', price : 3000},
    { title : 'Product 4', price : 4000}
  ]
  mongo.collection('products').insertMany(data, (err, r) => {
    console.log('documents inserted  : ',r.insertedCount)
    client.close()
  })
...

การแสดงข้อมูล

สำหรับการแสดงข้อมูลทั้งหมดสามารถทำได้โดยใช้ method ชื่อ find() แล้วยัดข้อมูลล
Array ซึ่งเราสามารถนำไปใช้งานต่อได้

...
...
    mongo.collection('products').find().toArray((err, result) => {
        console.log(result)
        client.close()
    })
...

ในกรณีต้องการแสดงข้อมูลเฉพาะ ก็สามารถทำได้กำหนดเงื่อนไข เช่น หากต้องการแสดงสินค้าที่มีการราคาเท่ากับ 2000 บาท ก็กำหนดให้แสดงข้อมูลดังนี้


    query = { price : 2000 } 
    mongo.collection('products').find(query).toArray((err, result) => {
        console.log(result)
        client.close()
    })
...

การแก้ไขข้อมูล

ในกรณีต้องการแก้ไขข้อมูล เราสามารถทำได้กำหนดชุดข้อมูลที่ต้องการแก้ไข สามารถกำหนด _id ที่ต้องการแก้ไข { _id : new MongoID.ObjectID('5d9c4eab7e4eda0b7418f0b8')

และกำหนดข้อมูลที่ต้องการแก้ไข
data = { $set: { price: 5555 }}

แล้วแก้ไขข้อมูลด้วย method ชื่อ updateOne() ซึ่งเป็นการแก้ไข 1 ชุด

...
...
    const MongoID = require('mongodb').ObjectID
...
...
    query = { _id : new MongoID.ObjectID('5d9c4eab7e4eda0b7418f0b8') }
    data = { $set: { price: 6000 }}

    mongo.collection('products').updateOne(query,data, (err, r) => {
        console.log("document updated")

        client.close()
    })
...

การลบข้อมูล

ในกรณีที่ต้องการข้อมูลสามารถทำได้โดยกำหนด _id ที่ต้องการลบแล้วเรียกใช้ method ชื่อ deleteOne() ดังตัวอย่าง

...
...
    const MongoID = require('mongodb').ObjectID
...
...
    query = { _id : new MongoID.ObjectID('5d9c4eab7e4eda0b7418f0b8') }

    mongo.collection('products').deleteOne(query,(err, r) => {
        console.log("document deleted")

        client.close()
    })
...
})

สรุป

สำหรับการติดต่อฐานข้อมูล Mongo สามารถใช้งานมอดูลชื่อ mongodb โดยมี method ให้เราเลือกใช้มากมาย ตัวอย่างเช่น insertOne() ,insertMany(), find(), updateOne() , deleteOne() ซึ่งสามารถเข้าไปดูรายละเอียดเพิ่มเติมที่ https://www.npmjs.com/package/mongodb

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more