1

i'm trying to pass the mongodb connection to all the other routes, so i created another file and imported mongoClient there and wrapped connect and getDb in functions so i can connect to the db first from server.js and then access the db from the other files, but idk why i'm getting Cannot read property 'collection' of undefined

server.js

const express = require('express')
const bodyParser = require('body-parser')
const mongodb = require('./mongodb/db.js')
const auth = require('./routes/auth.js')
require('dotenv').config()

const app = express();
app.use(bodyParser.json());
const PORT = process.env.PORT

app.get('/api', (req, res) => {
    res.send('Welcome to the api')
})

app.use('/api/auth', auth);


mongodb.connect(() => {
    app.listen(PORT, () => {
        console.log(`app is listening at http://localhost:${PORT}`)
    })
})

./mongodb/db.js

const MongoClient = require('mongodb').MongoClient;
const DB_URL = process.env.DB_URL
const DB_NAME = process.env.DB_NAME
const dbClient = new MongoClient(DB_URL, { useUnifiedTopology: true })

let db;

const connect = (callback) => {
    dbClient.connect().then(client => {
        db = client.db(DB_NAME)
        console.log("connected to db")
    }).catch(console.log)

    callback()
}

const get = () => {
    return db;
}

module.exports = {
    connect,
    get
};

./routes/auth.js

const express = require('express')
const router = express.Router();
const db = require('../mongodb/db.js');

const smth = db.get();
console.log(smth) //undefined;


const usersCollection = db.get().collection('users');
const authCollection = db.get().collection('auth')

router.post('/login', async (req, res) => {
    ...
})

router.post('/register', async (req, res) => {
    ...
})

module.exports = router

1 Answer 1

1

You call callback outside of the promise chain in the connect function of ./mongodb/db.js. It's possible that you are running into some async issues there, as the function can return before the promise chain resolves.

Sign up to request clarification or add additional context in comments.

2 Comments

still undefined
I did some more investigation. The issue here is execution order. Namely, the code in auth.js executes before mongodb.connect. If the code's entry point is server.js, then L5&6 of auth.js get executed before mongodb.connect is called. you need to rearrange your code such that db.get is called after mongodb.connect.

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.