Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
not able to acces db() from exported MongoClient module

I am not able to export the client properly from db.js to User.js

db.js

const some= MongoClient.connect(process.env.CONNECTIONSTRING).then((client) =>{
    module.exports=client
    const app = require("./app")
    app.listen(process.env.PORT)
})

Using the client here , i can do methods like client.db().collection("users");

But i am not able to do using the user.js

User.js

const usersCollection = require("../db").db().collection("users");

This gives error saying const

usersCollection = require("../db").db().collection("users");
                                         ^
TypeError: require(...).db is not a function
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I maybe wrong but in the callback function for MongoClient the first argument is the error and second argument is for client.(err,client)

so you are calling db() on error and not client

And also try to export from global scope as mentioned by Maxime in the comment

about 4 years ago · Juan Pablo Isaza Report

0

You have this problem because you are importing something that is asynchronous and when you do it in 1 line the client is not ready when you try to call it with db().collection("users").

You can verify if the async is the issue by changing your code to this:

const temp = require("../db")

setTimeout(() => {
  temp.db().collection("users")
}, 1000)

You can also check here for an example how to do the connection to the DB properly https://www.terlici.com/2015/04/03/mongodb-node-express.html

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!