サイトアイコン WEBデザインMATOME

Node.jsでのデータベース操作: MongoDBとMySQL

Node.jsはその非同期の特性により、データベース操作においても優れたパフォーマンスを発揮します。
このセクションでは、Node.jsで最も一般的に使用される2つのデータベース、
NoSQLのMongoDBとリレーショナルデータベースのMySQLの設定と接続方法、
さらにはCRUD操作までを解説します。

MongoDBの設定と接続

MongoDBはドキュメント指向のNoSQLデータベースで、大量のデータと高速な処理が要求されるアプリケーションに適しています。Node.jsとMongoDBを連携させるには、mongooseライブラリをよく使用します。

Mongooseのインストール

プロジェクトディレクトリで次のコマンドを実行して、mongooseをインストールします。

npm install mongoose

接続の設定

Mongooseを使用してMongoDBに接続する基本的なコードは以下の通りです。

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("We're connected!");
});

CRUD操作

MongoDBでデータモデルを定義し、CRUD操作を実行する例を示します。

const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

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

// Create
const alice = new User({ name: 'Alice', age: 25 });
alice.save().then(() => console.log('User Created'));

// Read
User.find().then(users => console.log(users));

// Update
User.findOneAndUpdate({ name: 'Alice' }, { age: 26 }).then(() => console.log('User Updated'));

// Delete
User.deleteOne({ name: 'Alice' }).then(() => console.log('User Deleted'));

MySQLの設定と接続

MySQLは広く使用されているリレーショナルデータベース管理システムです。Node.jsでMySQLデータベースに接続するためには、mysqlライブラリが一般的です。

mysqlのインストール
npm install mysql

接続の設定

MySQLデータベースへの接続設定は次のようになります。

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'yourUsername',
  password: 'yourPassword',
  database: 'mydatabase'
});

connection.connect(err => {
  if (err) throw err;
  console.log('Connected to MySQL!');
});

CRUD操作

MySQLでのCRUD操作の基本的な例を示します。

// Create
connection.query('INSERT INTO users (name, age) VALUES ("Bob", 30)', (err, result) => {
  if (err) throw err;
  console.log('User Created');
});

// Read
connection.query('SELECT * FROM users', (err, results) => {
  if (err) throw err;
  console.log(results);
});

// Update
connection.query('UPDATE users SET age = 31 WHERE name = "Bob"', (err, result) => {
  if (err) throw err;
  console.log('User Updated');
});

// Delete
connection.query('DELETE FROM users WHERE name = "Bob"', (err, result) => {
  if (err) throw err;
  console.log('User Deleted');
});

まとめ

MongoDBとMySQLはNode.jsアプリケーションで広く使われているデータベースです。それぞれのデータベースは異なる種類のデータ管理ニーズに応じて選ばれ、Node.jsの非同期処理能力と組み合わせることで、高性能でスケーラブルなアプリケーションを構築することが可能です。適切なライブラリと明確な設定を用いることで、データベースの操作も非常にシンプルかつ効率的に行えます。

モバイルバージョンを終了