Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda