LoginSignup
45
18

More than 5 years have passed since last update.

Node.jsのMongoClientの仕様が変わってた

Posted at

さっきnpmインストールしていつも通り接続しようとしたら TypeError: db.collection is not a function になるので調べてみたら、3系から仕様が変わったみたいです。

MongoClient.connect now returns a Client instead of a DB
http://mongodb.github.io/node-mongodb-native/3.0/upgrade-migration/main/

使い方

変更前

const MongoClient = require("mongodb").MongoClient;

const _url = 'mongodb://heroku_xxxxxxxx:lvojimq4uc5lu7fnljpg5b2vig@ds999999.mlab.com:49511/heroku_xxxxxxxx';

MongoClient.connect(_url, (err, db) => {
  db.collection('foobar', (err, collection) => {
    collection.find().toArray((err, docs) => {
      :
      :

    });
  });
});

変更後

const MongoClient = require("mongodb").MongoClient;

const _url = 'mongodb://heroku_xxxxxxxx:lvojimq4uc5lu7fnljpg5b2vig@ds999999.mlab.com:49511/heroku_xxxxxxxx';

MongoClient.connect(_url, (err, client) => {
  // callbackに渡されるオブジェクトが変わった
  // db名を明示的に指定してdbオブジェクトを取得する必要がある
  const db = client.db('heroku_xxxxxxxx');

  db.collection('foobar', (err, collection) => {
    collection.find().toArray((err, docs) => {
      :
      :

    });
  });
});
45
18
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
45
18