Search code examples
javascriptreactjsnode.jsmongodbexpress

TypeError: Cannot read properties of undefined (reading 'collection') (mongodb connection)


am trying to connect the mongodb database and i get the error as shown below

It gives me error

TypeError: Cannot read properties of undefined (reading 'collection')
    at C:\Users\Joh\Desktop\chipsproject\server\server.js:22:14
    at Layer.handle [as handle_request] (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\route.js:149:13)
    at Route.dispatch (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\route.js:119:3)
    at Layer.handle [as handle_request] (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\Joh\Desktop\chipsproject\server\node_modules\express\lib\router\index.js:280:10)
    at cors (C:\Users\Joh\Desktop\chipsproject\server\node_modules\cors\lib\index.js:188:7)
    at C:\Users\Joh\Desktop\chipsproject\server\node_modules\cors\lib\index.js:224:17

my connection file is as follow

const Express = require('express')
const app = Express()
const cors = require('cors')
app.use(cors());
const MongoClient = require('mongodb').MongoClient


var database;

app.listen(5000, ()=>{
    MongoClient.connect('mongodb://localhost:27017/chips', (err, client)=>{
        database=client.db('chips');
        console.log('connected to database');
    })

})

app.get('/user',(request,response)=>{
    database.collection('users').find({}).toArray((err,results)=>{
        if (err) throw err

        response.send(results);
    })
})

thank youj,i will appreceate your response


Solution

  • TypeError: Cannot read properties of undefined (reading 'collection')

    The problem is that your database variable is being accessed before it's initialized. This happens because the connection to MongoDB is asynchronous, and your server might be handling requests before the database connection is established.

    Try this instead for databse-connection.

    let database;
    
    MongoClient.connect('mongodb://localhost:27017/chips')
        .then(client => {
            database = client.db('chips'); // you can also use this "client.db();"
            console.log('Connected to database');
    
            // Start the server only after successful DB connection
            app.listen(5000, () => {
                console.log('Server is running on port 5000');
            });
        })
        .catch(err => console.error(err));
    

    After that you can perform rest of the database operation as per your need.

    Try this,it will work.

    Suggestion :-

    Have you ever though that when you need database instance to other module how would you do that ?

    --> Though it is my suggestion not the fixed rule,you should define database-connection to a separate module and based on your need you should import it to other module.

    To know how to do that please check the below link where I have answered the question.

    https://stackoverflow.com/a/78689128/21210375