Not populating mongoDB database with data being entered on angular

I am writing a post form function using MEAN stack which saves the data to the DB.
When entering the data through postman on the node, express, mongoose side it stores in the database. however when entering the date through the angular frontend, the data isnt storing, this method i used for other forms and it worked however this one just doesn’t:

HTML:

<form [formGroup]="form" (submit)="addMessage()">
            <mat-form-field>
              <mat-label>Username:</mat-label>
              <input
                placeholder="Username"
                matInput
                formControlName="username"
                class="form-control"
                type="string"
                required
              />
            </mat-form-field>
            <br />
            <mat-form-field>
              <mat-label>Message:</mat-label>
              <input
                placeholder="Type Message Here..."
                matInput
                formControlName="message"
                class="form-control"
                type="string"
                required
              />
            </mat-form-field>
            <br />
            <mat-form-field>
              <mat-label>Message Date:</mat-label>
              <input
                placeholder="Type Message Here..."
                matInput
                formControlName="messageDateTime"
                class="form-control"
                type="date"
                required
              />
            </mat-form-field>
            <br />
            <button mat-raised-button color="basic" type="submit">Send</button>
            <br />
            <mat-divider></mat-divider>
          </form>

Typescript:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { MessageBoardService } from 'src/app/service/message-board.service';
import { Message } from 'src/app/models/messages.interface';

@Component({
  selector: 'app-message-board',
  templateUrl: './message-board.component.html',
  styleUrls: ['./message-board.component.css']
})
export class MessageBoardComponent implements OnInit {
  messages: Message[] = [];

  constructor(private messageService: MessageBoardService) { }
  form = new FormGroup({
    username: new FormControl(''),
    message: new FormControl(''),
    messageDateTime: new FormControl(''),
  });


  addMessage() {
    console.log('adding');
    const formData = new FormData();
    formData.append('username', this.form.value.username);
    formData.append('message',this.form.value.message);
    formData.append('messageDateTime',this.form.value.messageDateTime);
    this.messageService.postMessage(formData).subscribe((d) => {
      console.log(d);
    });
    //window.location.reload();
  }

  ngOnInit(): void {
    this.messageService.getMessage().subscribe((M: Message[]) => {
      this.messages = M;
    })
  }

}

Service:

postMessage(data: any){
    return this.http.post<any>("http://localhost:3000/Messages", data)
    .pipe(map((res:any)=>{
      return res;
    }))
  }

The get function works fine in the services it is only the post.
Posting data using postman works well, but from the frontend it just saves the default data that is set in the mongoose schema

Schema:

const mongoose = require('mongoose');

const MessagesSchema = new mongoose.Schema({
    username:{
        type: String,
        required: false,
        default: "User"
    },
    message:{
        type: String,
        required: false,
        default:"Content"
    },
    messageDateTime:{
        type: Date,
        required: false,
        default: Date.now
    }
})

    
const Messages = mongoose.model( 'Messages', MessagesSchema);

module.exports =  Messages

Data Entered Using Angular Frontend:

Not populating mongoDB database with data being entered on angular

Data Saved in Database:
(Console Output):

{username: ‘User’, message: ‘Content’, messageDateTime:
‘2022-03-04T23:23:32.040Z’, _id: ‘62229f740a9c53a525774f01’, __v: 0}
message: “Content” messageDateTime: “2022-03-04T23:23:32.040Z”
username: “User”
__v: 0
_id: “62229f740a9c53a525774f01” [[Prototype]]: Object

(Data stored accessed by postman):

{
“_id”: “62229f740a9c53a525774f01”,
“username”: “User”,
“message”: “Content”,
“messageDateTime”: “2022-03-04T23:23:32.040Z”,
“__v”: 0
},

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I’m not sure why do you need FormData, as I have never used it in Angular

I generally send data like this to backend

let dataToSend: any = {
  username: this.form.value.username,
  message: this.form.value.message,
  messageDateTime: this.form.value.messageDateTime
}

this.messageService.postMessage(dataToSend).subscribe((d) => {
  console.log(d);
});

I’ll also update the service and Content-Type header, assuming your backend is expecting JSON.

let headers = new Headers();
headers.append('Content-Type', 'application/json');

postMessage(data: any)
{
  http.post('http://localhost:3000/Messages', JSON.stringify(data), {
   headers : headers
 }).pipe('Rest of the Code');
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x