Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
19
Help us understand the problem. What is going on with this article?
@mimizq

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

More than 3 years have 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) => {
      :
      :

    });
  });
});
19
Help us understand the problem. What is going on with this article?
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
mimizq
Javaを7年やってPHP2年生。Node.jsもちょっと。PHPのぬるさにびっくりしている。わりと有名なサービスやってる会社のあんまり有名じゃないほうのサービス担当。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
19
Help us understand the problem. What is going on with this article?