TypeError: db.collection is not a function

2,157 views
Skip to first unread message

Vlad Bukov

unread,
Mar 27, 2018, 2:00:33 PM3/27/18
to node-mongodb-native
Why do I get this error  "db.collection is not a function" when starting this example? 

var MongoClient = require('mongodb').MongoClient,
test = require('assert');
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

// Create a collection we want to drop later
var collection = db.collection('simple_query');

// Insert a bunch of documents for the testing
collection.insertMany([{a:1}, {a:2}, {a:3}], {w:1}, function(err, result) {
test.equal(null, err);

// Perform a simple find and return all the documents
collection.find().toArray(function(err, docs) {
test.equal(null, err);
test.equal(3, docs.length);

db.close();
});
});
});

Jorge Mayo Martín

unread,
Apr 3, 2018, 4:00:30 PM4/3/18
to node-mongodb-native
Hi Vlad,
  since the version 3.0 of node-mongodb-native driver the way to connect to the mongodb server is a little bit different; check this link: http://mongodb.github.io/node-mongodb-native/3.0/quick-start/quick-start/#connect-to-mongodb

Maybe check too the error object first of use the db connection; for example:
if (err) return process.exit(1)
Reply all
Reply to author
Forward
0 new messages