Haɗa Express.js aikace-aikacenku tare da ma'ajin bayanai muhimmin mataki ne na haɓaka aikace-aikacen gidan yanar gizo masu ƙarfi da bayanai. Wannan jagorar za ta ɗauke ku ta hanyar samar da haɗin kai tsakanin Express.js app ɗinku da bayanan bayanai kamar MongoDB da MySQL, yana ba ku damar adanawa da dawo da bayanai yadda yakamata.
Haɗa zuwa MongoDB
Shigar da Direban MongoDB: Fara ta hanyar shigar da direban MongoDB don Node.js ta amfani da npm.
npm install mongodb
Ƙirƙiri Haɗin kai: A cikin aikace-aikacen ku Express.js, kafa hanyar haɗi zuwa bayanan MongoDB na ku.
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();
});
Haɗa zuwa MySQL
Sanya MySQL Driver: Shigar da direba na MySQL don Node.js ta amfani da npm.
npm install mysql
Ƙirƙiri Haɗin kai: Haɗa Express.js ƙa'idar ku zuwa bayanan 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();
});
Yin Ayyukan Database
Saka bayanai: Yi amfani da hanyoyin da suka dace don saka bayanai a cikin bayananku.
// 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);
});
Mai da Bayanai: Nemo bayanai daga bayananku.
// 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);
});
Kammalawa
Haɗa Express.js aikace-aikacen ku zuwa bayanan bayanai kamar MongoDB ko MySQL yana buɗe yuwuwar adana bayanai da sarrafa ingantaccen aiki. Ta bin waɗannan matakan, za ku kasance da wadataccen kayan aiki don ƙirƙirar aikace-aikacen yanar gizo waɗanda ke yin hulɗa tare da bayanan bayanai ba tare da ɓata lokaci ba, ba ku damar isar da ƙaƙƙarfan gogewar bayanai ga masu amfani da ku.