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();
}