Node.js で MongoDB に接続
MongoDBは、C++で書かれたドキュメント指向データベース管理システムです。
この章では、Node.js を使用して MongoDB に接続し、データベースを操作する方法を紹介します。
MongoDB の基礎知識がない場合は、次のチュートリアルを参照してください:MongoDB チュートリアル。
ドライバーのインストール
本チュートリアルでは淘宝がカスタマイズした cnpm コマンドを使用してインストールします:
$ cnpm install mongodb
インストールが成功すると、MongoClient オブジェクトを使用してデータベースに接続できます:
例
const { MongoClient } = require('mongodb');
async function main() {
// MongoDB 接続 URI
const uri = "mongodb://localhost:27017"; // リモートの MongoDB を使用している場合は、URI を適宜変更してください
// 新しい MongoClient を作成
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
// MongoDB サーバーに接続
await client.connect();
console.log("Connected successfully to server");
} finally {
// 完了後に接続を閉じることを確認
await client.close();
}
}
main().catch(console.error);
上記のコードを実行すると、出力結果は次のようになります:
Connected successfully to server
接続パラメータの説明:
MongoClient:これは MongoDB のクライアントで、データベースに接続するために使用します。uri:これは MongoDB の接続文字列で、形式は次のとおりです。mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]。useNewUrlParserとuseUnifiedTopologyは、いくつかの古い接続動作を避けるためのオプションです。
次に、追加・削除・更新・検索(CRUD)機能を実装します。
データベースの作成
MongoDB にデータベースを作成するには、まず MongoClient オブジェクトを作成し、指定した URL とポート番号を設定する必要があります。
データベースが存在しない場合、MongoDB はデータベースを作成し、接続を確立します。
接続の作成
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功");
const database = client.db('サンプル');
const collection = database.collection('exampleCollection');
const doc = { name: "Example", type: "Test" };
const result = await collection.insertOne(doc);
console.log(`新しいドキュメントが作成されました。IDID は: ${result.insertedId}`);
} finally {
await client.close();
}
}
main().catch(console.error);
上記のコードを実行すると、出力結果は次のようになります:
成功连接到服务器
新文档已创建,ID 为: 6678e18e0bb3f4247be610d8
コレクションの作成
createCollection() メソッドを使用してコレクションを作成できます:
コレクションの作成
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成成功`);
const collection = database.collection(collectionName);
const doc = { name: "Example", type: "Test" };
const result = await collection.insertOne(doc);
console.log(`新しいドキュメントが作成されました。IDID は: ${result.insertedId}`);
} finally {
await client.close();
}
}
main().catch(console.error);
上記のコードを実行すると、出力結果は次のようになります:
成功连接到服务器
集合 exampleCollection 创建成功
新文档已创建,ID 为: 6678e1b5c742b3ebd57f9759
データベース操作(CURD)
MySQL と異なり、MongoDB はデータベースとコレクションを自動的に作成するため、使用前に手動で作成する必要はありません。
データの挿入
次の例では、データベース サンプル の exampleCollection コレクションに接続し、1件のデータを挿入します。 insertOne():
1件のデータを挿入
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成成功`);
const collection = database.collection(collectionName);
const doc = { name: "Alice", age: 25, address: "Wonderland" };
const result = await collection.insertOne(doc);
console.log(`新しいドキュメントが作成されました。IDID は: ${result.insertedId}`);
} finally {
await client.close();
}
}
main().catch(console.error);
上記のコマンドを実行すると、出力結果は次のようになります:
成功连接到服务器
集合 exampleCollection 创建成功
新文档已创建,ID 为: 6678e1d1f9503dc2e0e2a20b
出力結果から、データが正常に挿入されたことがわかります。
MongoDB のクライアントを開いてデータを確認することもできます。例:
> show dbs
サンプル 0.000GB # 创建了 サンプル 数据库
> use サンプル # 切换到 サンプル 数据库
サンプル> show tables
exampleCollection # 创建了 exampleCollection 集合(数据表)
# 自动创建了 site 集合(数据表)
サンプル> db.exampleCollection.find()
[
{
_id: ObjectId('6678e1d1f9503dc2e0e2a20b'),
name: 'Alice',
age: 25,
address: 'Wonderland'
}
]
複数件のデータを挿入する場合は、次を使用できますinsertMany():
複数件のデータを挿入
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成成功`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました。IDID は:`);
Object.keys(result.insertedIds).forEach((key, index) => {
console.log(`ドキュメント ${index + 1}: ${result.insertedIds[key]}`);
});
} finally {
await client.close();
}
}
main().catch(console.error);
実行すると、出力結果は次のようになります:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 6678e30e80ac30e5e689f13a
文档 2: 6678e30e80ac30e5e689f13b
文档 3: 6678e30e80ac30e5e689f13c
データのクエリ
find() を使用してデータを検索できます。find() は一致する条件のすべてのデータを返します。
条件を指定しない場合、find() はコレクション内のすべてのデータを返します。
find()
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成成功`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました。IDID は:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const query = {};
const options = { projection: { _id: 0, name: 1, age: 1, address: 1 } };
const cursor = collection.find(query, options);
const allValues = await cursor.toArray();
console.log("クエリされたドキュメント:");
console.log(allValues);
} finally {
await client.close();
}
}
main().catch(console.error);
実行すると、出力結果は次のようになります:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 0
文档 2: 1
文档 3: 2
查询到的文档:
[
{ name: 'Alice', age: 25, address: 'Wonderland' },
{ name: 'Bob', age: 30, address: 'Builderland' },
{ name: 'Charlie', age: 35, address: 'Chocolate Factory' }
]
次の例では、name が "Alice" のデータを検索します:
指定した条件のデータをクエリ
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成成功`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました、ID次のとおりです:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const query = { name: "Alice" };
const options = { projection: { _id: 0, name: 1, age: 1, address: 1 } };
const cursor = collection.find(query, options);
const allValues = await cursor.toArray();
console.log("クエリされたドキュメント:");
console.log(allValues);
} finally {
await client.close();
}
}
main().catch(console.error);
以下のコマンドを実行すると、出力結果は次のようになります:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 0
文档 2: 1
文档 3: 2
查询到的文档:
[
{ name: 'Alice', age: 25, address: 'Wonderland' }
]
データの更新
データベースのデータを変更することもできます。次の例では、name が "Alice" のデータを更新します:
1件のデータを更新
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功しました");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成に成功しました`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました、ID次のとおりです:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const filter = { name: "Alice" };
const updateDoc = {
$set: {
age: 28,
address: "New Wonderland"
},
};
const updateResult = await collection.updateOne(filter, updateDoc);
console.log(`${updateResult.matchedCount}件のドキュメントがフィルター条件に一致しました`);
console.log(`${updateResult.modifiedCount}件のドキュメントが更新されました`);
const updatedDocument = await collection.findOne(filter);
console.log("更新されたドキュメント:");
console.log(updatedDocument);
} finally {
await client.close();
}
}
main().catch(console.error);
実行が成功すると、出力結果は次のようになります:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 0
文档 2: 1
文档 3: 2
1 个文档匹配筛选条件
1 个文档已更新
更新后的文档:
{
_id: new ObjectId('6678e1d1f9503dc2e0e2a20b'),
name: 'Alice',
age: 28,
address: 'New Wonderland'
}
条件に一致するすべてのドキュメントデータを更新する場合は、使用できますupdateMany():
複数件のデータを更新
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功しました");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成に成功しました`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Alice", age: 28, address: "Old Wonderland" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました、ID次のとおりです:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const filter = { name: "Alice" };
const updateDoc = {
$set: {
address: "Updated Wonderland"
},
};
const updateResult = await collection.updateMany(filter, updateDoc);
console.log(`${updateResult.matchedCount}件のドキュメントがフィルター条件に一致しました`);
console.log(`${updateResult.modifiedCount}件のドキュメントが更新されました`);
const updatedDocuments = await collection.find(filter).toArray();
console.log("更新されたドキュメント:");
console.log(updatedDocuments);
} finally {
await client.close();
}
}
main().catch(console.error);
データの削除
次の例では、name が "Alice" のデータを削除します:
1件のデータを削除
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功しました");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成に成功しました`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました、ID次のとおりです:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const filter = { name: "Alice" };
const deleteResult = await collection.deleteOne(filter);
console.log(`${deleteResult.deletedCount}件のドキュメントが削除されました`);
const remainingDocuments = await collection.find({}).toArray();
console.log("残りのドキュメント:");
console.log(remainingDocuments);
} finally {
await client.close();
}
}
main().catch(console.error);
実行が成功すると、出力結果は次のようになります:
成功连接到服务器
集合 exampleCollection 创建成功
3 个新文档已创建,ID 为:
文档 1: 0
文档 2: 1
文档 3: 2
1 个文档已删除
剩余的文档:
[
{
_id: new ObjectId('6678e18e0bb3f4247be610d8'),
name: 'Example',
type: 'Test'
},
...
複数のデータを削除する場合は、使用できますdeleteMany()メソッド
次の例では、type が en のすべてのデータを削除します:
複数件のデータを削除
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功しました");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成に成功しました`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Alice", age: 28, address: "Old Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました、ID次のとおりです:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const filter = { name: "Alice" };
const deleteResult = await collection.deleteMany(filter);
console.log(`${deleteResult.deletedCount}件のドキュメントが削除されました`);
const remainingDocuments = await collection.find({}).toArray();
console.log("残りのドキュメント:");
console.log(remainingDocuments);
} finally {
await client.close();
}
}
main().catch(console.error);
並べ替え
ソートには sort() メソッドを使用します。このメソッドは1つの引数を受け取り、昇順(1)か降順(-1)を指定します。
例:
{ type: 1 } // 按 type 字段升序
{ type: -1 } // 按 type 字段降序
type の昇順で並べ替え:
並べ替え
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功しました");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成に成功しました`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" },
{ name: "Dave", age: 20, address: "Dreamland" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました、ID次のとおりです:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const sortedDocsAsc = await collection.find().sort({ age: 1 }).toArray();
console.log("age フィールドの昇順に並べ替えた後のドキュメント:");
console.log(sortedDocsAsc);
const sortedDocsDesc = await collection.find().sort({ age: -1 }).toArray();
console.log("age フィールドの降順に並べ替えた後のドキュメント:");
console.log(sortedDocsDesc);
} finally {
await client.close();
}
}
main().catch(console.error);
クエリのページネーション
返す件数を指定する場合は、使用できますlimit()メソッド。このメソッドは1つのパラメータのみを受け取り、返す件数を指定します。
limit():2件のデータを読み取る
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功しました");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成に成功しました`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" },
{ name: "Dave", age: 20, address: "Dreamland" },
{ name: "Eve", age: 22, address: "Eden" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました、ID次のとおりです:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const limitedDocs = await collection.find().limit(3).toArray();
console.log("クエリ結果を3件のドキュメントに制限:");
console.log(limitedDocs);
} finally {
await client.close();
}
}
main().catch(console.error);
スキップする件数を指定する場合は、使用できますskip()メソッド。
skip() メソッドは、指定した数のドキュメントをスキップし、残りのドキュメントのクエリ結果を返します。
skip(): 先頭の2件をスキップして、2件のデータを読み取る
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功しました");
const database = client.db('サンプル');
const collectionName = 'exampleCollection';
await database.createCollection(collectionName);
console.log(`コレクション ${collectionName}作成に成功しました`);
const collection = database.collection(collectionName);
const docs = [
{ name: "Alice", age: 25, address: "Wonderland" },
{ name: "Bob", age: 30, address: "Builderland" },
{ name: "Charlie", age: 35, address: "Chocolate Factory" },
{ name: "Dave", age: 20, address: "Dreamland" },
{ name: "Eve", age: 22, address: "Eden" }
];
const result = await collection.insertMany(docs);
console.log(`${result.insertedCount}件の新しいドキュメントが作成されました、ID次のとおりです:`);
Object.keys(result.insertedIds).forEach((id, index) => {
console.log(`ドキュメント ${index + 1}: ${id}`);
});
const skippedDocs = await collection.find().skip(2).toArray();
console.log("最初の2つのドキュメントをスキップした後のクエリ結果:");
console.log(skippedDocs);
} finally {
await client.close();
}
}
main().catch(console.error);
接続操作
mongoDB はリレーショナルデータベースではありませんが、私たちは使用できます$lookupを使用して左結合を実装できます。
$lookup は、MongoDB で左外部結合(left outer join)を実行するための集約パイプライン演算子です。あるコレクション内で、別のコレクションの条件に一致するドキュメントを検索し、それらを結合するために使用できます。
例えば、次の2つのコレクションデータがあるとします:
コレクション1:orders
[
{ "_id": 1, "product_id": 101, "quantity": 2 },
{ "_id": 2, "product_id": 102, "quantity": 1 },
{ "_id": 3, "product_id": 103, "quantity": 4 }
]
コレクション2:products
[
{ "_id": 101, "name": "Product A", "price": 50 },
{ "_id": 102, "name": "Product B", "price": 70 },
{ "_id": 103, "name": "Product C", "price": 100 },
{ "_id": 104, "name": "Product D", "price": 120 }
]
ここで、$lookup 操作を使用して orders コレクションの product_id フィールドと products コレクションの _id フィールドを関連付け、各注文の製品詳細情報を取得したいとします。
以下は、この機能を実装するための MongoDB 集約の例です:
例
const { MongoClient } = require('mongodb');
async function main() {
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log("サーバーへの接続に成功しました");
const database = client.db('mydatabase');
const ordersCollection = database.collection('orders');
const productsCollection = database.collection('products');
const pipeline = [
{
$lookup: {
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'productDetails'
}
}
];
const result = await ordersCollection.aggregate(pipeline).toArray();
console.log("左外部結合のクエリ結果:");
console.log(result);
} finally {
await client.close();
}
}
main().catch(console.error);
コレクションの削除
私たちは使用できますdrop()メソッドでコレクションを削除します:
drop()
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("サンプル");
dbo.collection("test").drop(function(err, delOK) {
if (err) throw err;
if (delOK) console.log("コレクションが削除されました");
db.close();
});
});
Promise を使用
Promise は ECMAScript 6 で提供されるクラスで、複雑な非同期タスクをよりエレガントに記述することを目的としています。
Promise についてまだよく知らない場合は、以下を参照してくださいJavaScript Promise。
次のインスタンスは Promise を使用してコレクションを作成します:
例
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
function connectDB() {
return new Promise((resolve, reject) => {
client.connect((err) => {
if (err) {
reject(err);
} else {
console.log("MongoDB サーバーへの接続に成功しました");
resolve(client.db());
}
});
});
}
connectDB()
.then(database => {
console.log("データベースへの接続に成功しました");
console.log("データベース名:", database.databaseName);
client.close();
})
.catch(err => {
console.error("データベース接続時にエラーが発生しました:", err);
});
Promise データ操作
ここで、1つのプログラムで4つの連続操作(追加、クエリ、変更、削除)を実装します。
例
const { MongoClient, ObjectId } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
function connectDB() {
return new Promise((resolve, reject) => {
client.connect((err) => {
if (err) {
reject(err);
} else {
console.log("MongoDB サーバーへの接続に成功しました");
resolve(client.db());
}
});
});
}
function insertDocument(db, document) {
const collection = db.collection('documents');
return new Promise((resolve, reject) => {
collection.insertOne(document, (err, result) => {
if (err) {
reject(err);
} else {
console.log("ドキュメントの追加に成功しました");
resolve(result);
}
});
});
}
function findDocuments(db) {
const collection = db.collection('documents');
return new Promise((resolve, reject) => {
collection.find({}).toArray((err, docs) => {
if (err) {
reject(err);
} else {
console.log("ドキュメントのクエリ結果:");
console.log(docs);
resolve(docs);
}
});
});
}
function updateDocument(db, id, updatedValues) {
const collection = db.collection('documents');
return new Promise((resolve, reject) => {
collection.updateOne({ _id: ObjectId(id) }, { $set: updatedValues }, (err, result) => {
if (err) {
reject(err);
} else {
console.log("ドキュメントの更新に成功しました");
resolve(result);
}
});
});
}
function deleteDocument(db, id) {
const collection = db.collection('documents');
return new Promise((resolve, reject) => {
collection.deleteOne({ _id: ObjectId(id) }, (err, result) => {
if (err) {
reject(err);
} else {
console.log("ドキュメントの削除に成功しました");
resolve(result);
}
});
});
}
async function performOperations() {
try {
const database = await connectDB();
const insertResult = await insertDocument(database, { name: "Document 1" });
const findResult = await findDocuments(database);
const updatedDocId = insertResult.insertedId;
const updateResult = await updateDocument(database, updatedDocId, { name: "Updated Document 1" });
const deleteResult = await deleteDocument(database, updatedDocId);
console.log("最終操作が完了しました:");
console.log("ドキュメントの削除結果:", deleteResult);
} catch (err) {
console.error("操作の実行中にエラーが発生しました:", err);
} finally {
await client.close();
}
}
performOperations();
実行結果:
数据库已连接
[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]
[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]
[]
その他の拡張