Setup and Configure MongoDB
Sign-up for MongoDB Atlas account
Open your browser and go to https://cloud.mongodb.com
Then click on Try Free to create a free account. The free account provides a sandbox for the MongoDB database (limited to 500MB).
After you sign-up, answer the various questions accordingly and click on Finish
Select the Shared cloud database option and click Create.
Choose AWS as the Cloud Provider and a Region that provides a free tier (Singapore is one of them). The default Cluster Tier is M0 Sandbox.
Amend the Cluster Name to FWEBCluster and Click on Create Cluster.
A new cluster is being created. Wait for a few minutes for the clusters to be created. Once the cluster is created, the Security Quickstart screen will appear.
Select Username and Password as the Authentication Method and enter “test1” for username, “testone1” for password and click on the Create User button. So, now you have a user account when you need to access the database.
Note: Take note of the database user privileges here as you might want to create users with different privileges type in the future for the purpose of authorization.
Next, we will be enabling our network access for our MongoDB cluster. Select the My Local Environment option and enter 0.0.0.0 for the IP Address and click on the Add Entry button. By enabling
Note: In a real-world application, we should not be using Allow Access from Anywhere. But for this exercise, we will be using it to simplified our database configuration.
Once we have successfully configured our network access, click on the Finish and Close button to complete our initial configuration!
You will be redirected to the following Database deployments screen
To recap: MongoDB is a no-SQL database that uses collections to store data.
We have successfully created our first MongoDB database and completed the configuration. Take some time to look at the various buttons and information within this page and get familiarize with the user interface.
Install MongoDB library in our meanApp project
After successfully setting up our MongoDB, we will proceed to enhance our meanApp project to facilitate the connection between our back-end web server with the database.
Open Visual Studio Code, Select File > Open Folder (Crtl + K, Crtl + O) and open up meanApp project (Note: You have to completed Mini-Project 9 before you can proceed with this portion of the lab exercise)
Select Terminal > New Terminal (Crtl + Shift + `) and press enter to open up the terminal (command prompt) inside Visual Studio Code.
Then, to install MongoDB into the project, type in the following: npm install mongodb --save
Wait a few minutes for the MongoDB packages to be installed and be automatically added to the project.
In this exercise, we will be focusing on creating the connection between our back-end web server with MongoDB.
Update the api.js file
Open the file api.js
Before we can establish a connection in our code to the MongoDB database, we need to know the connection string. This can be found in the Atlas dashboard by choosing Database from the left-hand navigation menu, then click on the Connect button and then click on the Connect Your Application option.
Follow the instruction accordingly, copy the connection string in step 2 and replace the and myFirstDatabase variables with our newly created database information.
Note: Your password should be testone1 and your database name should be miniprojectDB if you are following the exercise correctly. We will be creating our miniprojectDB later on in the lab exercise.
Example: mongodb+srv://test1:@fwebcluster.llalc.mongodb.net/myFirstDatabase?retryWrites= true&w=majority
to
mongodb+srv://test1:testone1@fwebcluster.llalc.mongodb.net/miniprojectDB?retryWrites=true &w=majority
Update the api.js file to include the following codes to do the following:
Connect our back-end web server to MongoDB using the MongoClient and the connection-string.
Add a new /posts HTTP POST route to insert a record into the posts collection in MongoDB
const express = require('express');
const router = express.Router();
// declare axios for making http requests
const axios = require('axios');
const API = 'https://jsonplaceholder.typicode.com';
// get API listing
router.get('/', (req, res) => {
res.send('api works');
});
const MongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
var db;
MongoClient.connect('connection-string', { useNewUrlParser: true ,
useUnifiedTopology: true }, (err, database) => {
if (err) return console.log(err);
db = database.db('miniprojectDB');
});
// create new post
router.route('/posts).post(function (req, res) {
db.collection('posts').insertOne(req.body, (err, results) => {
if (err) return console.log(err);
console.log('saved to database');
res.send(results);
});
});
module.exports = router;
Note: Replace or comment away the previous codes for the route /posts
Note: Replace the connection string above with your own DB connection string from MongoDB.
We had successfully created our MongoDB cluster and connects our back-end application with it. In the codes above, you can see that we are trying to do an insert into a DB collection “posts”. Collections in a NoSQL database is equivalent to tables in a relational database.
Next, let’s create our miniprojectDB and the posts collection inside MongoDB.
In your Database Deployments screen in MongoDB, click on the Browse Collections button to start creating our database and adding new collection into our database.
Create on Add My Own Data and a popup should appear, enter miniprojectDB as the database name and posts as the collection name and click on the Create button
You can now see that your miniprojectDB have been successfully created and the posts collection have been added into your database.
Now that we have created our posts collection in our MongoDB, let’s amend some codes in our front-end web application’s posts service to perform an insert post function HTTP POST request to our back-end web server.
Update the posts.service.ts file
Open the file posts.service.ts
Update the file to include a function insertPost() to make a POST API call:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostsService {
constructor(private http: HttpClient) { }
url: string = "http://localhost:3000/api/posts";
getAllPosts() {
return this.http.get<any[]>(this.url);
}
insertPost(name: string, newpost: number) {
return this.http.post<any[]>(this.url, { 'name': name, post: newpost });
}
}
Update the app.component.html file
Open the file app.component.html
Update the file to include a form to insert data:
<div class="container">
<div class="row">
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="container">
<div class="row">
<div class="col-sm-12">
<p>
<input formControlName="name" id="name" placeholder="name">
<input formControlName="post" id="post" placeholder="post">
<button class="btn btn-primary" type="submit">Submit</button>
</p>
</div>
</div>
</div>
</form>
</div>
</div>
Update the app.component.ts file
1. Open the file app.component.ts
2. For this file, we are doing the following:
Import OnInit lifecycle hook from angular core library
Import FormBuilder and FormGroup from angular form library
Inject FormBuilder into App Component
Create a FormGroup object call myForm
Implement OnInit lifecycle hook and initialize the myForm object
Create a function call onSubmit which invoke the postsService’s insertPost function
3. Update the file to bind to the data from the HTML form:
import { Component, OnInit } from '@angular/core';
import { PostsService } from './posts.service';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'List of Posts';
posts: any = [];
myForm!: FormGroup;
constructor(private postsService: PostsService, private fb: FormBuilder) {
// Retrieve posts from the API
this.postsService.getAllPosts().subscribe(posts => {
this.posts = posts;
});
}
ngOnInit() {
this.myForm = this.fb.group({
name: '',
post: ''
});
}
onSubmit(){
this.postsService.insertPost(this.myForm.value.name, this.myForm.value.post).subscribe(results => {
location.reload();
});
}
}
Update the app.module.ts file
Open the file app.module.ts
Update the file to import and include the ReactiveFormModules library in the imports array:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { PostsService } from './posts.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
ReactiveFormsModule
],
providers: [PostsService],
bootstrap: [AppComponent]
})
export class AppModule {}
Build and Run the Back-end Application
To run our back-end application using Express, we need to re-build the app.
So, type in the following into the command prompt window: ng build
Then, run the server by typing in the following (check that you are in the same location as server.js before executing the command): node server.js Run the Front-end Application
To run the app, type in the following into the command prompt window: ng serve
A lot of messages will appear. Wait for the message ‘Compiled successfully’ line to appear. It will take several minutes. Once this appears it means the app is running.
Open Google Chrome browser and type in: http://localhost:4200/
You will see the following displayed on the browser:
Then, let’s say you type in “Survey”, “1231” and click submit, you will see saved to database being print in your terminal:
Finally go back to the cloud.mogodb.com and click on the Database on the left-hand navigation menu then click on Browse Collections button. Select miniprojectDB > posts collection, you will see the a document with _id, name and post added under the posts collection.
Therefore, this shows the data submitted in the form has been successfully inserted into the MongoDB database.
Displaying the data from MongoDB - Select
For the second part of the project, you will enhance the existing meanApp to display the data from MongoDB on the HTML page. You can reuse what you had learn in the previous mini project as a reference. (Make use of ng-bootstrap to achieve better styling for your website)
Expected output:
Let’s say you type in “Mary”, “70” and click submit, you will see the new record on the HTML page. If you go back to MongoDB and click on the Database tab, you will see a new document has been successfully inserted into the posts collection.
References:
https://angular.io/guide/lifecycle-hooks
https://www.upwork.com/hiring/data/sql-vs-nosql-databases-whats-the-difference/
https://www.npmjs.com/package/axios
https://www.mongodb.com/
https://zellwk.com/blog/crud-express-mongodb/
In this lesson, you have successfully:
Signup for account with MongoDB Atlas
Install MongoDB for your back-end web application
Insert data as a collection in MongoDB
Retrieve data from a collection in MongoDB
Hire Expert to get help in Angular with MongoDB Database. We are group of top rated angular expert and professionals that can help you to complete your business and industrious projects.
To get help you can contact us at:
realcode4you@gmail.com
Kommentarer