Konektivitas Database ing Express.js: Nyambung menyang MongoDB lan MySQL

Nggabungake aplikasi sampeyan Express.js karo database minangka langkah penting kanggo mbangun aplikasi web sing dinamis lan adhedhasar data. Pandhuan iki bakal nuntun sampeyan liwat proses nggawe sambungan antarane Express.js aplikasi lan basis data kaya MongoDB lan MySQL, supaya sampeyan bisa nyimpen lan njupuk data kanthi efisien.

Nyambung menyang MongoDB

Instal Driver MongoDB: Miwiti kanthi nginstal driver MongoDB kanggo Node.js nggunakake npm.

npm install mongodb

Gawe Sambungan: Ing Express.js aplikasi sampeyan, gawe sambungan menyang database MongoDB.

const MongoClient = require('mongodb').MongoClient;  
const url = 'mongodb://localhost:27017/mydb';  
  
MongoClient.connect(url,(err, client) => {  
  if(err) throw err;  
  const db = client.db('mydb');  
  // Perform database operations  
  client.close();  
});  

Nyambung menyang MySQL

Instal Driver MySQL: Instal driver MySQL kanggo Node.js nggunakake npm.

npm install mysql

Nggawe Sambungan: Sambungake Express.js app menyang database MySQL.

const mysql = require('mysql');  
const connection = mysql.createConnection({  
  host: 'localhost',  
  user: 'root',  
  password: 'password',  
  database: 'mydb'  
});  
  
connection.connect((err) => {  
  if(err) throw err;  
  // Perform database operations  
  connection.end();  
});  

Nindakake Operasi Database

Lebokake Data: Gunakake cara sing cocog kanggo nglebokake data menyang database sampeyan.

// MongoDB  
db.collection('users').insertOne({ name: 'John', age: 30 });  
  
// MySQL  
const sql = 'INSERT INTO users(name, age) VALUES(?, ?)';  
connection.query(sql, ['John', 30],(err, result) => {  
  if(err) throw err;  
  console.log('Record inserted: ' + result.affectedRows);  
});  

Njupuk Data: Njupuk data saka database sampeyan.

// MongoDB  
db.collection('users').find({}).toArray((err, result) => {  
  if(err) throw err;  
  console.log(result);  
});  
  
// MySQL  
const sql = 'SELECT * FROM users';  
connection.query(sql,(err, result) => {  
  if(err) throw err;  
  console.log(result);  
});  

 

Kesimpulan

Nyambungake Express.js aplikasi sampeyan menyang database kaya MongoDB utawa MySQL mbukak kunci potensial kanggo panyimpenan lan manajemen data sing efisien. Kanthi ngetutake langkah-langkah iki, sampeyan bakal dilengkapi kanthi apik kanggo nggawe aplikasi web sing sesambungan kanthi lancar karo database, ngidini sampeyan ngirim pengalaman sing kuat lan adhedhasar data menyang pangguna.