I would recommend you to use the new async await functionality introduced in more recent Javascript versions to start with. This form is easier to reason about since it looks like a normal synchronous code. Grasping Javascript's async nuances will take some time, but eventually you'll need it to understand how Javascript works using multiple async methods: Promises, callbacks, etc.
The shortest async/await code using express & MongoDB that I can come up with is this one:
const MongoClient = require('mongodb').MongoClient
const express = require('express')
const app = express()
var conn
app.get('/', async (req, res) => {
var output = await conn.db('test').collection('test').find().toArray()
res.send(output)
})
var run = async function() {
conn = await MongoClient.connect('mongodb://localhost:27017/test', {useNewUrlParser: true})
await app.listen(3000)
console.log('listening on 3000')
}
run()
Using curl "http://localhost:3000" should print the content of the test collection in the test database.
Some things to note:
conn is a global variable to allow the MongoDB driver to properly use connection pooling. Connect once and reuse the connection everywhere. Don't keep connecting to the database for every request.
- The main
run() method sets up the database connection, then starts listening. This way you're ensuring that the database is ready to go. Otherwise your app can start listening before the database is ready.
- The example code above does not have any error handling method. In real code, you should use
try {...} catch {...} as needed.
This code was tested with node 12.4.0, MongoDB node driver 3.2.7, and express 4.17.1
If you find that this code doesn't work, please make sure that you can connect to the database.