0

I'm trying send data from a MongoDB server to the client on a GET request. I'm using an express server and want to send all the documents in a specific collection when a GET request is received.

I know MongoDB is asynchronous, so I query an asynchronous function with a promise. I am able to log to console all the documents in the MongoDB Collection but when I return it the data becomes undefined. I have a database called 'testDB' and I want to return all the documents in a specific collection ('testCollection').



app.get('/getData', (req, res) => {
    returnData().then(result => {
        console.log(result); //This logs undefined
        res.send(result); //This sends undefined
    })
});



async function returnData() {
    const uri = "mongodb+srv://" + "username" + ":" + "password" + "@" + "connection url" + "/?retryWrites=true&w=majority";

    //Connect to the database and return all documents in the collection
    const client = new MongoClient(uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
    try {
        await client.connect();
        const database = client.db('testDB');
        const collection = database.collection('testCollection');
        const query = {};
        const options = {};
        const cursor = collection.find(query, options);
        await cursor.toArray().then((docs) => {
            console.log(docs); // <- This works and logs all the data to console 
            return docs;
        });
    } catch (e) {
        console.error(e);
    } finally {
        await client.close();
    }
}

EDIT:

I tried this and it returns undefined.

try {
    await client.connect();
    const database = client.db('testDB');
    const collection = database.collection('testCollection');
    const query = {};
    const options = {};
    const cursor = collection.find(query, options);
    await cursor.toArray().then((docs) => {
        return cursor.toArray();
    });
} catch (e) {
    console.error(e);
} finally {
    await client.close();
}

I tried this and I get [MongoPoolClosedError]: Attempted to check out a connection from closed connection pool

try {
    await client.connect();
    const database = client.db('testDB');
    const collection = database.collection('testCollection');
    const query = {};
    const options = {};
    const cursor = collection.find(query, options);
    return cursor.toArray();
} catch (e) {
    console.error(e);
} finally {
    await client.close();
}
Wriar
  • 306
  • 1
  • 10
  • Does this answer your question? [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) – Phil Dec 12 '22 at 03:14
  • The last line of your `try` block should be `return cursor.toArray();`. Wrecking your promise chain just to log some data that's in your DB anyway seems an odd choice – Phil Dec 12 '22 at 03:14
  • Tried return ``cursor.toArray();`` inside the await and it returns undefined. Tried removing the await and putting it directly in the try statement and I get TypeError [ERR_INVALID_ARG_TYPE]. – Wriar Dec 12 '22 at 03:19
  • I'm having a hard time imagining the code you're using so please [edit] your question – Phil Dec 12 '22 at 03:21
  • I've added my two attempts. – Wriar Dec 12 '22 at 03:28
  • The last one is correct syntactically. You should search using that new error message for solutions – Phil Dec 12 '22 at 03:29
  • I added a ``setTimeout(() => {client.close()}, 1500);`` in the ``finally`` section. I'm not sure if this is the best way to do it but I do get the returned data. Thanks. – Wriar Dec 12 '22 at 03:32
  • 1
    Most MERN apps create a connection when the app starts, not on-demand. See https://www.mongodb.com/languages/mern-stack-tutorial – Phil Dec 12 '22 at 03:33

1 Answers1

0

Don't open and close the mongo client on each GET. Connect once and export that connection to your other modules. In terms of the Express request/response. You hand it off something like below.

app.get('/getData', myAsyncFunction)

async function index (req, res) {
  let r = await db.collection("testDB").find(query).toArray();
  return res.send(r);
}
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91