0

[nodemon] starting node server.js C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\utils.js:725 throw error; ^

TypeError: Cannot read property 'db' of undefined at C:\Users\Abhay\Desktop\todo-app\server.js:8:17 at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\utils.js:722:9 at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\mongo_client.js:223:23 at C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\operations\connect.js:279:21 at QueryReqWrap.callback (C:\Users\Abhay\Desktop\todo-app\node_modules\mongodb\lib\core\uri_parser.js:56:21) at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:10) [nodemon] app crashed - waiting for file changes before starting...

let express = require('express')
let mongodb = require('mongodb')
let app = express()
let db

let connectionString = 'mongodb+srv://todoAppUser:[email protected]/TodoApp?retryWrites=true&w=majority'
mongodb.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
    db = client.db()
    app.listen(3000)
})
3

1 Answer 1

1

It seems you're trying to use the static connect method of MongoClient to make a connection to your db, but you are not using the MongoClient class itself.

To connect to any db, you will need a connected instance of MongoClient. Using the static connect method, you can achieve it in the following way:

const mongodb = require("mongodb");


const connectionURL = "mongodb+srv://your-connection-srv-here"
const dbName = "your_db_name"

//get MongoClient
const MongoClient = mongodb.MongoClient;

let db = null;

MongoClient.connect(connectionURL,{
    useNewUrlParser: true,
    useUnifiedTopology: true
},(err,connectedClient) => {
    if(err){
        throw err;
    }
    //connectedClient will be the connected instance of MongoClient
    db = connectedClient.db(dbName);
    //now you can write queries

    db.collection("your_collection").find({}).toArray()
    .then(r => {
        console.log(r);
    }).catch(e => {
        console.error(`ERROR:`,e);
    })

})

However, using callbacks will be quite cumbersome. As per the docs linked above, most functions in the MongoDb driver for Node.js will return a promise if a callback function is not passed, which is very convenient. Using this, you can write a function which return a promise that resolves a connected instance to your db.

const MongoClient = require('mongodb').MongoClient;


/*
    we draw the connection srv and the db name from the config to return just one instance of that db.
    Now this function call be called wherever a connection is needed
*/
const getDbInstance = (config) => new Promise((resolve,reject) => {
    const client = new MongoClient(config.dbUrl, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
    client.connect((error) => {
        if(error){
            console.error(error);
            reject(error);
        }
        let db = client.db(config.dbName);
        resolve(db);
    })
})


const doSomeDbOperations = async() => {
    //hardcoding it here, but this config will probably come from environment variables in your project
    const config = {
        dbUrl: "mongodb+srv://your-connection-srv-here",
        dbName: "your_db_name"
    };

    try{
        const db = await getDbInstance(config);

        //do whatever querying you wish here

    }catch(e){
        console.error(`ERROR: `,e);
    }

}

doSomeDbOperations();
Sign up to request clarification or add additional context in comments.

Comments

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.