LoginSignup
11
14

More than 5 years have passed since last update.

MongoDBでAsync/Await

Last updated at Posted at 2018-07-09

Node.jsでMongoDBの公式ドライバーでAsync/Awaitを使う例です。

※ 2019/3/23: エラー処理を追加してコードを見直しました。

const transaction = async () => {
  let client;
  try {
    client = await mongodb.MongoClient.connect("mongodb://127.0.0.1:27017", {
      useNewUrlParser: true
    });

    const db = client.db("DATABSE_NAME");

    const res = await db
      .collection("COLLECTION_NAME")
      .save({ key: "value" });

    const docs = await db
      .collection("COLLECTION_NAME")
      .find({})
      .toArray();
    return docs;
  } catch (error) {
    console.log(error);
  } finally {
    client.close();
  }
};

transaction();

まとめ

  • エラー処理をfinally句で行えるので楽
  • 同期APIと非同期APIが混在しているので注意
11
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
14