0

I want to return "items" which is inside the for loop and also two additional functions."Items" is an object (I would not say variable) which consists of three array elements and that can be more depending on the situation. So I need to return "items" so I can access it outside and I can send it to the client using res.send(). If I send data inside the loop and function, it is returning with an error called "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client". I found the fix for it but on implementing them, nothing is happening. It is throwing me the same error. I was thinking to do it call back function but I am confused about how to use it in this case. Thanks in advance.

router.get("/send" , async (req, res) => {
try {
    res.send("hello")
     //await sendData()
     getCollectionNames()
  } catch (error) {
    console.log(error);
  }
function getCollectionNames(){
    MongoClient.connect(url, function(err, db) {
    var db = db.db('admin')
    mongoose.connection.db.listCollections().toArray(function (err, names) {
        for(let index = 0; index < names.length; index ++){
            if (err) {
            console.log(err);
            }
            let name = names[index].name
            const collection = db.collection(name)
            collection.find().toArray(function(err, items){
                console.log(items)
            })   
    }

    });
})
}

})

Heb99
  • 11
  • 4
  • And also forgot to add one more thing is that I will use "items" more than once. So it will be great if we find a solution in which I can use that "items" object more than once – Heb99 Jun 23 '20 at 22:47
  • You have lots of issues here. Start with this: [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323) because you can't return ANY value from `getCollectionNames()` that was retrieved asynchronously and you have several asynchronous values in their already. – jfriend00 Jun 23 '20 at 22:49
  • For better and more complete help, explain what you're actually trying to accomplish in your `router.get("/send", ...)` route because there are likely better ways to attack the problem than what you're asking about. – jfriend00 Jun 23 '20 at 22:50
  • And, start reading about the promise interface to your database (instead of the plain callback interface you are currently using) because that's going to be part of the better way to approach this problem too. – jfriend00 Jun 23 '20 at 22:52
  • I am just trying to send "items" which is the object that has three arrays as of right now to the client using router.get(). And items is the object that has all the elements that are present in databse – Heb99 Jun 23 '20 at 23:25

0 Answers0