Home > Software design >  not able to acces db() from exported MongoClient module
not able to acces db() from exported MongoClient module

Time:01-19

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

CodePudding user response:

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

CodePudding user response:

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

  •  Tags:  
  • Related