MEAN app with Angular 4 (Part 5) Saving data to MongoDb

In this part we will post a data from angular to node.js and save it to mongoDb. I’m going to use mlab for mongoDb. If you don’t have an account yet with mlab, you can register at https://mlab.com/.

Login to your mlab account. Then in create new MongoDb.

mongo db

Select the amazon web services as cloud provider and sandbox for plan type. Then click continue.

aws region

Select your desired aws region then click continue.

aws region

Then give a name for your database. I called mine as events_db then click continue.

create db using mlab

Click submit order to create your database.

submit order

Now open your newly created database and you will see the connection string. You will notice that it requires you a database username and password.

mongodb connection string

To create a username and password for our mongoDb click the Users tab. Then in users tab click Add database user button.

add new user

Fill up the form for username and password. I used admin for username and also admin for password. Then click the create button.

create user for mongo db

Now open your node js project and in integrated terminal, execute the command.

npm install --save mongoose

In our node js project create a new folder named models then a new file inside the models folder and call it Event.js.

var mongoose = require('mongoose')

module.exports = mongoose.model('Event', {
    title: String,
    description: String,
    destination: String,
    meetUpPlace: String,
    date: Date
})

We need to install another library to parse the data that will be posted from the front-end. Install body-parse by executing this command in your integrated terminal.

npm install body-parser --save

In server.js we will require the mongoose and body-parse to use in our project. We will also update our get events code to get the data from mongoDb then add the post method to create a new event. Update your server.js code to look like the code below.

var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var mongoose = require('mongoose')
var app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

var Event = require('./models/Event.js')

app.use(cors())

app.get('/events', async (req, res) => {
    var events = await Event.find({});
    res.send(events);
})

app.post('/events', (req, res) => {
    var eventData = req.body;
    var event = new Event(eventData);

    event.save((err, result) => {
        if (err) {
            console.log("error saving event.")
        }

        res.sendStatus(200);
    })
})

mongoose.connect('mongodb://admin:admin@ds133776.mlab.com:33776/events_db')

app.listen(3000)

Now we also need to add changes for our frontend project to post the data in the backend. Open your frontend project then update your code in the app.service.ts to add the postEvents function.

import { Http } from '@angular/http';
import { Injectable } from '@angular/core';

@Injectable()
export class AppService {
    events = [];

    constructor( private http: Http) {}

    getEvents() {
        this.http.get('http://localhost:3000/events').subscribe(res => {
            this.events = res.json();
        });
    }

    postEvents(newEventData) {
        this.http.post('http://localhost:3000/events', newEventData).subscribe(res => {
        });
    }
}

Finally change your code in events-register.components.ts to use the postEvents function.

ackend. Open your frontend project then update your code in the app.service.ts to add the postEvents function.

import { Component } from '@angular/core';
import { AppService } from './app.service';

@Component({
  selector: 'events-register',
  templateUrl: './events-register.component.html'
})
export class EventRegisterComponent {

    newEventData = {}    

    constructor( private appService: AppService) {}

    post() {
        this.appService.postEvents(this.newEventData);
    }

    cancel() {
        this.newEventData = {};
    }    

}

Let’s try if everything is working. Run your application and add a new event.

add event using form

If everything is working well, you should see now a data in your mongoDb.

data save in the mongodb

Related Articles

Source Code

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s