Cannot read Property 'Collection' of Undefined

Asked

Viewed 553 times

0

Error:

TypeError: Cannot read property 'collection' of undefined
    at Object.findAll (/Users/filipealves/node/crud/db.js:7:17)
    at /Users/filipealves/node/crud/routes/index.js:6:13
    at Layer.handle [as handle_request] (/Users/filipealves/node/crud/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/filipealves/node/crud/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/filipealves/node/crud/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/filipealves/node/crud/node_modules/express/lib/router/layer.js:95:5)
    at /Users/filipealves/node/crud/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/filipealves/node/crud/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/filipealves/node/crud/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/filipealves/node/crud/node_modules/express/lib/router/index.js:174:3)

Code:

const mongoClient = require('mongodb').MongoClient
mongoClient.connect('mongodb:/localhost:27017/workshop')
.then(conn => global.conn = conn.db('workshop'))
.catch(err => console.log(err));

function findAll(callback) {
    global.conn.collection('customers').find({}).toArray(callback);
};

module.exports = {findAll};

  • 3

    Hello Felipe, welcome to Stackoverflow PT. To get a better answer from the community it would be good if you explained more about your problem and gave a Title the question in English

  • Try to specify better what your problem is, what you’re trying to do and what you’re not getting. Change the title of your question to English as well. Don’t paste the mistake here until someone comes and solves it. Edit your question so we can get along better.

  • Filipe at first his error occurs because his global object.Conn is undefined, it is possible that this occurred due to the connection method being asynchronous.

  • The mistake means that global.conn === undefined, I may be wrong, but I believe the problem lies in passing the name of the bank to the mongoClient.connect('mongodb:/localhost:27017/workshop') and then try to select a bank in conn.db('workshop'). It would be like trying to access the database of another database. But I’m not sure. Try to change global.conn = conn.db('workshop') for global.conn = conn

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.