LoginSignup
5
1

More than 5 years have passed since last update.

node.js から mongodb 3.0.10 で繋ぐ with async / await

Last updated at Posted at 2018-06-24

node.js から npm の mongodb 3.0.10 で mongo に async / await を使って接続する方法のメモです。
検索で 2.2 系のドキュメントが上位に来るのですが、 2.2 系と 3.0 系で API が変わっていて少しハマったので書き留めます。

インストール

手元の mac に入れるという想定で mongodb のインストール

brew install mongodb

npm パッケージインストール

yarn add mongodb
yarn add --dev babel-cli babel-preset-es2015

.babelrc

{ "presets": ["es2015"] }

サンプルコード

mongoDB のチュートリアルにはコールバックを使った方法が書かれてますが、実は promise を返してくれるのでそっちを使ったほうがスッキリ書けます。
es2015 の async / await を使ったサンプルコードがこちら。
一件だけドキュメントを挿入する接続テストを行います。

import mongodb from 'mongodb'

const HOSTNAME = 'mongodb://127.0.0.1:27017'
const DB_NAME = 'test_database'
const COLLECTION_NAME = 'test_collection'

const main = async () => {
  const client = await mongodb.MongoClient.connect(HOSTNAME)
  const db = await client.db(DB_NAME)
  const collection = db.collection(COLLECTION_NAME)
  await collection.insert({ foo: "bar" })
  client.close()
}

main()

実行結果

実行します。

babel src -d dist
node dist/test.js

結果確認します。

$ mongo

> show databases
......(略)
test_database  0.000GB

> use test_database

> db.test_collection.find()
{ "_id" : ObjectId("5b2f5118b0284648fa8df6b7"), "foo" : "bar" }

オッケー!

関連

関連: Node.jsからMongoDBに接続してみる
参考: mongoDB quick start (node.js driver 3.x)

5
1
0

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
5
1