Building the API - querying products
Once the database is set up and ready, you need to establish a connection with it. That's what you're going to do in this part of the course. Apart of that you will create backend API to get list of products and their descriptions.
Building the API#
Once your MongoDB instance is set up and fed with data, it's time to build an API that retrieves that data from the DB and serves it to the API consumer. Install the necessary dependencies:
npm i mongodb cors body-parser saslprep@1.0.0
Creating API - products endpoints#
Create a new file called api.ts (in the same directory as backend.ts) and add the following code:
import * as express from 'express';
import * as cors from 'cors';
import * as bodyParser from 'body-parser';
export const api = express.Router();
api.use(
cors({
origin: true,
credentials: true,
})
);
api.use(bodyParser.json());
The code above introduces the express.Routing()
object and sets up the middleware that you are going to use.
Connecting to the database#
To respond to an API client with a product list or user data, you first need to retrieve it from MongoDB. It's time to instantiate a connection with your MongoDB instance.
Add the following import statements to api.ts:
import { ObjectId, MongoClient } from 'mongodb';
Set up a connection with the database:
const dbUrl =
'mongodb+srv://angular-universal:[email protected]';
const dbClient = MongoClient.connect(dbUrl, {
useUnifiedTopology: true,
}).then((connection) => connection.db('cluster0'));
dbClient.then(() => {
console.log('Connected to the database.');
});
Remember to replace the connection string and database name with your database-specific data.
Beware that database name which you provide in the connection.db()
method must match database name in your Atlasian account. Otherwise your program will fail silently - instead of returning data your API will respond with empty arrays and objects.

This page is a preview of The newline Guide to Angular Universal