21
loading...
This website collects cookies to deliver better user experience
audit-log-demo
and a collection named user-profile
.
audit-log-demo
as part of the database list.Now, let's add test data to our database.
audit-log-demo
database. You will be directed to the collection list page.user-profile
collection. You will be directed to the collection management page.In the Insert to Collection popup, paste the following properties just below the _id property:
"firstName": "Tony",
"lastName": "Stark",
"age": 25
npm init
. Follow the prompts and provide the necessary details.express
and the mongodb
driver by executing npm install mongodb express --save
ALD_CONN_STRING
and set its value to your connection string.At the root of your working directory, create an index.js
file with this content:
const { MongoClient, ObjectId } = require('mongodb');
const express = require('express');
const mongoConnString = process.env.ALD_CONN_STRING;
const mongoClient = new MongoClient(mongoConnString);
const expressApp = express();
const expressPort = 3000;
expressApp.get('/profile', async (req, res, next) => {
try {
await mongoClient.connect();
const db = mongoClient.db('audit-log-demo');
const col = db.collection('user-profile');
const profileList = await col.find({}).toArray();
res.send({
data: profileList
});
} catch (err) {
next(err);
}
finally {
await mongoClient.close();
}
});
expressApp.listen(expressPort, () => {
console.log(`Example app listening at http://localhost:${expressPort}`)
});
In the above code, we used the ALD_CONN_STRING
environment variable to retrieve the connection string. Then, we instantiated the MongoDB and Express clients. We also introduced one route (/profiles
) which retrieves all the documents in the user-profile
collection.
Run your application by executing node index.js
on your CLI.
Then, using your favorite REST client (I'm using Postman), access the /profiles
endpoint of your API. You should get this result:
{
"data": [
{
"_id": "<GUID>",
"firstName": "Tony",
"lastName": "Stark",
"age": 25
}
]
}
index.js
file just before the listen
call:expressApp.get('/profile/:id', async (req, res, next) => {
try {
await mongoClient.connect();
const db = mongoClient.db('audit-log-demo');
const col = db.collection('user-profile');
const profile = await col.findOne({ _id: ObjectId(req.params.id) });
res.send({
data: profile
});
} catch (err) {
next(err);
}
finally {
await mongoClient.close();
}
});
index.js
code at this point by clicking here.expressApp.get('/profiles', async (req, res, next) => {
try {
await mongoClient.connect();
const db = mongoClient.db('audit-log-demo');
const col = db.collection('user-profile');
const profileList = await col.find({}).toArray();
res.send({
data: profileList
});
} catch (err) {
next(err);
}
finally {
await mongoClient.close();
}
});
expressApp.get('/profile/:id', async (req, res, next) => {
try {
await mongoClient.connect();
const db = mongoClient.db('audit-log-demo');
const col = db.collection('user-profile');
const profile = await col.findOne({ _id: ObjectId(req.params.id) });
res.send({
data: profile
});
} catch (err) {
next(err);
}
finally {
await mongoClient.close();
}
});
In both routes, the parts that connect to the database and retrieve a reference to the collection are repeated. We should always follow the DRY (Don't Repeat Yourself) principle!
async function dbConnBeforeware(req, res, next) {
const mongoConnString = process.env.ALD_CONN_STRING;
const mongoClient = new MongoClient(mongoConnString);
await mongoClient.connect();
console.log("Database connection established!");
req.dbClient = mongoClient;
req.dbDatabaseRef = mongoClient.db('audit-log-demo');
next();
}
async function dbConnAfterware(req, res, next) {
await req.dbClient.close();
console.log("Database connection closed!");
next();
}
async function getAllProfilesHandler(req, res, next) {
try {
const col = req.dbDatabaseRef.collection('user-profile');
const profileList = await col.find({}).toArray();
res.send({
data: profileList
});
next();
} catch (err) {
next(err);
}
}
async function getProfileByIdHandler(req, res, next) {
try {
const col = req.dbDatabaseRef.collection('user-profile');
const profile = await col.findOne({ _id: ObjectId(req.params.id) });
res.send({
data: profile
});
next();
} catch (err) {
next(err);
}
}
// For readability, we also created 2 new separate functions for the actual request handlers
expressApp.get('/profiles', dbConnBeforeware, getAllProfilesHandler, dbConnAfterware);
expressApp.get('/profile/:id', dbConnBeforeware, getProfileByIdHandler, dbConnAfterware);
index.js
code at this point by clicking here.expressApp.use(async function (err, req, res, next) {
if (req.dbClient) {
await req.dbClient.close();
console.log("Database connection closed!");
}
console.error(err.stack);
res.status(500).send('Something broke!');
});
index.js
code at this point by clicking here.getProfileByIdHandler
handler to simulate an error happening.dbConnBeforeware
can also be made configurable so you can use it for other routes that handle data from another collection.