Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

さっき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) => {
      :
      :

    });
  });
});
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした