MongoDB - TypeError: db.collection is not a function

Could someone give this a try and see if it’ll work for them? You’d need Node/NPM and MongoDB at v3.x

At the moment, it’s giving the following error, but I’m not seeing why:

##Console Error Message

➜  mongodb-script-project node mongodb-script.js
Connection is okay
/Users/christopherallanperry/development/edx_node/module_03/mongodb-script-project/node_modules/mongodb/lib/mongo_client.js:797
          throw err;
          ^

TypeError: db.collection is not a function
    at insertDocuments (/Users/christopherallanperry/development/edx_node/module_03/mongodb-script-project/mongodb-script.js:3:25)
    at MongoClient.connect (/Users/christopherallanperry/development/edx_node/module_03/mongodb-script-project/mongodb-script.js:63:3)
    at args.push (/Users/christopherallanperry/development/edx_node/module_03/mongodb-script-project/node_modules/mongodb/lib/utils.js:404:72)
    at /Users/christopherallanperry/development/edx_node/module_03/mongodb-script-project/node_modules/mongodb/lib/mongo_client.js:255:5
    at connectCallback (/Users/christopherallanperry/development/edx_node/module_03/mongodb-script-project/node_modules/mongodb/lib/mongo_client.js:933:5)
    at /Users/christopherallanperry/development/edx_node/module_03/mongodb-script-project/node_modules/mongodb/lib/mongo_client.js:794:11
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

##mongodb-script.js

const insertDocuments = (db, callback) => {
  // Get reference to edx-course-docs collection
  const collection = db.collection('edx-course-students')
  // Insert 3 documents
  collection.insert([
    {name : 'Bob'}, {name : 'John'}, {name : 'Peter'} // 3 documents
  ], (error, result) => {
    if (error) return process.exit(1)
    console.log(result.result.n) // will be 3
    console.log(result.ops.length) // will be 3
    console.log('Inserted 3 documents into the edx-course-students collection')
    callback(result)
  })
}

const updateDocument = (db, callback) => {
  // Get the edx-course-students collection
  var collection = db.collection('edx-course-students')
  // Update document where a is 2, set b equal to 1
  const name = 'Peter'
  collection.update({ name : name }, { $set: { grade : 'A' } }, (error, result) => {
      if (error) return process.exit(1)
      console.log(result.result.n) // will be 1
      console.log(`Updated the student document where name = ${name}`)
      callback(result)
  })
}

const removeDocument = (db, callback) => {
  // Get the documents collection
  const collection = db.collection('edx-course-students')
  // Insert some documents
  const name = 'Bob'
  collection.remove({ name : name }, (error, result) => {
    if (error) return process.exit(1)
    console.log(result.result.n) // will be 1
    console.log(`Removed the document where name = ${name}`)
    callback(result)
  })
}

const findDocuments = (db, callback) => {
  // Get the documents collection
  const collection = db.collection('edx-course-students')
  // Find some documents
  collection.find({}).toArray((error, docs) => {
    if (error) return process.exit(1)
    console.log(2, docs.length) // will be 2 because we removed one document
    console.log(`Found the following documents:`)
    console.dir(docs)
    callback(docs)
  })
}

const MongoClient = require('mongodb').MongoClient

// Connection URL
const url = 'mongodb://localhost:27017/edx-course-db'
// Use connect method to connect to the DB server
MongoClient.connect(url, (error, db) => {
  if (error) return process.exit(1)
  console.log('Connection is okay')
  insertDocuments(db, () => {
    console.log('insertDocuments() accessed')
    updateDocument(db, () => {
      removeDocument(db, () => {
        findDocuments(db, () => {
          db.close()
        })
      })
    })
  })
})

##package.json

{
  "name": "mongodb-script",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mongodb": "^3.0.1"
  }
}

The nearest I’ve found to an answer is in this SO thread - TypeError: db.collection is not a function
, but as far as I can see, I have my script set up correctly for a v3.x MongoDB environment, as per the response with ~59 up votes.

Version 3 does the connect differently where it gives the parent instead of the db.
See http://mongodb.github.io/node-mongodb-native/3.0/quick-start/quick-start/

You’ll want:

// MongoClient.connect(url, (error, db) => {
MongoClient.connect(url, (error, client) => {
  const db = client.db;
1 Like

Thanks Paul, I’ll give it a go in the morning.

Still no joy with this. I’m still seeing the same error message coming back in the console at the moment. I’ve thrown a bunch of console.log() statements in there, and as a cutdown version the file now looks like this

const insertDocuments = (db, callback) => {
  // Get reference to edx-course-docs collection
  console.log('The insertDocuments db is typeof: ' + typeof db)
  console.log('db.collection is typeof: ' + typeof db.collection)
  const collection = db.collection('edx-course-students')
  console.log('collection is typeof: ' + typeof collection)
  
  // Insert 3 documents
  collection.insert([
    {name : 'Bob'}, {name : 'John'}, {name : 'Peter'} // 3 documents
  ], (error, result) => {
    if (error) return process.exit(1)
    console.log(result.result.n) // will be 3
    console.log(result.ops.length) // will be 3
    console.log('Inserted 3 documents into the edx-course-students collection')
    callback(result)
  })
}

const MongoClient = require('mongodb').MongoClient

// Connection URL
const url = 'mongodb://localhost:27017/edx-course-db'
// Use connect method to connect to the DB server
MongoClient.connect(url, (error, client) => {
  // console.log('client is a typeof: ', typeof client + '\n')
  // console.log(client)
  const db = client.db
  // console.log('\n' + db  + '\n')
  // console.log('db (from client.db) is a typeof: ', typeof db + '\n')
  if (error) return process.exit(1)
  console.log('Connection is okay' + '\n')
  insertDocuments(db, () => {
    // console.log('insertDocuments() accessed')
    updateDocument(db, () => {
      removeDocument(db, () => {
        findDocuments(db, () => {
          db.close()
        })
      })
    })
  })
})

I’ve left out the update, remove and find functions, as they never get called into action. In the console, I’m getting the following:

###from the insertDocuments() function

typeof db is a function
typeof db.collection is undefined

###from the MongoClient.connect(url, (error, client) callback
typeof client is an object
typeof client.db is a function

In the MongoDB REPL, I can see that the database isn’t being created as I’d expect it to be, though a test I did yesterday showed that I could create it manually without a problem, though I’ve since dropped it.

Which instructions have you been following for using the Mongo database?

How do you mean? From an installation perspective, or how I’m using it?

Yes, from how you’re using it to interface with the API to the database.

For this one, I’m just running the file using the following command from the console

node mongodb-script.js

with mongod running in a separate tab.

Mongo was installed sometime around last November when I started my WDI course at GA. Whilst I’ve not really done a lot with it since then for various reasons, it has been working quite happily when I have needed it over the last year, usually accessing it using Angular and the Mongoose ODM though, rather than how it’s being done here.

It might not even be your script that’s causing the problem.

To help weed out issues and figure out where the problems lay, I recommend that you get a basic working database done using the crud guide

Edit:

That was the ESNext crud guide. I recommend instead the Mongo crud operations guide.

I’ll get some reading done then and get something fired up.

Pardon, that previous link was for ESNext.

The Mongo DB link that’s useful for initial testing of a database is this [Mongo crud operations]
(http://mongodb.github.io/node-mongodb-native/3.0/tutorials/crud/) guide.

1 Like

Noted…

Hi Chris,

As per that answer on StackOverflow, you need to reference your database by name to access the correct object.

This should work as intended.

const insertDocuments = (db, callback) => {
  const collection = db.collection('edx-course-students');

  collection.insert(
    [{ name: 'Bob' }, { name: 'John' }, { name: 'Peter' }],
    (error, result) => {
      if (error) return process.exit(1);
      callback(result);
    }
  );
};


const MongoClient = require('mongodb');

const url = 'mongodb://localhost:27017/edx-course-db';

MongoClient.connect(url, (error, database) => {
  if (error) return process.exit(1);
  console.log('Connection is okay');

  const db = database.db('edx-course-db');

  insertDocuments(db, () => {
    console.log('Insert successful');
  });
});
2 Likes

Thanks @James_Hibbard, I’ve got it at last. I think I was looking at this way too late last night and hadn’t really digested what was being said on that SO thread. I will though spend some time with the pages @paul_wilkins posted though and see what else I can learn.

2 Likes

I Thank you too. You also solved my problem. I was going crazy and it took me 2 weeks to finally find the correct direction.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.