1

when I use "mongodb": "^3.0.5",

    const cn = require('./connect');

    function showItems(req, callback) {
      cn.MongoClient.connect(cn.url, (err, database)=> {

        const collection = database.db.collection('items');

        collection.find({}).toArray((err, result)=> {

          callback(result);
        });

        database.close();
      })
    }

    module.exports = showItems;

I got,

/node_modules/mongodb/lib/mongo_client.js:433

throw err

^

TypeError: database.db.collection is not a function

But,when I use "mongodb": "^2.2.33" , it worked.

    const cn = require('./connect');

    function showItems(req, callback) {
      cn.MongoClient.connect(cn.url, (err, db)=> {

        const collection = db.collection('items');

        collection.find({}).toArray((err, result)=> {

          callback(result);
        });

        db.close();
      })
    }

    module.exports = showItems;

connect.js

    const url = "mongodb://127.0.0.1:27017/databasename";
    const MongoClient = require('mongodb').MongoClient;

    module.exports = {url, MongoClient};

Use "mongodb": "^3.0.5" , How to solve this problem ?

2
  • don't know how this works in earlier version, Here is a guide that may help using later/latest version github.com/usman154/movieApp Commented Apr 4, 2018 at 9:28
  • What does your ./connect do ? If you want to use cn.MongoClient.connect you shoud replace const cn = require('./connect'); by const cn = require('mongodb'); Commented Apr 4, 2018 at 9:33

2 Answers 2

1

I think this is permission error.so we need to get the database first then try to access the collections. will solve the problem.

const MongoClient = require('mongodb').MongoClient;
const cn = require('./connect');

MongoClient.connect(cn.url, (err, database) => {
  if (err) {
    console.log(err);
    throw err;
  } else {
    const myDB = database.db('myDatabaseName')
    const collection = myDB.collection('items');
    collection.find({}).toArray((err, result) => {
      callback(result);
    });
    db.close();
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

still this issue
then uninstall mongo from npm js & reinstall npm package will solve your problem.
0

Try with :

client.collection()

instead.

The connect method return the database object.

2 Comments

TypeError: client.collection is not a function
Did you check the err value ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.