LoginSignup
9

More than 5 years have passed since last update.

Node.jsからmongoDB操作でのdb.collection is not a functionでハマった

Last updated at Posted at 2018-02-06

mongoDBドライバのバージョンアップ

2017年12月にmongoDB Node.js Driverが3.0にアップデートした模様。

今までの書き方でdb.collection is not a function出てハマりました。

version 2.2

test.js
const MongoClient = require('mongodb').MongoClient;

const url = "mongodb://localhost:27017/plactice";

MongoClient.connect(url, (err, db) => {
    db.collection("test", (error, collection) => {
        collection.insertMany([
            { name: 'Bob', age: 24 },
            { name: 'john', age: 30 }
        ], (error, result) => {
            db.close();
        });
    });
});

version 3.0

test.js

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

const url = "mongodb://localhost:27017/plactice";

MongoClient.connect(url, (err, client) => {  //dbからclientに変更
    const db = client.db("plactice")  // 追加
    db.collection("test",(error, collection) => {
        collection.insertMany([
            { name: 'Bob', age: 24 },
            { name: 'john', age: 30 }
        ],(error,result) => {
            client.close();  //db.close()から変更
        });
    });
});

connectの引数のコールバックが今までdbだったものがclientに。

無事にSuccess。

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
9