Home > Net >  Not populating mongoDB database with data being entered on angular
Not populating mongoDB database with data being entered on angular

Time:03-05

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"
                
                type="string"
                required
              />
            </mat-form-field>
            <br />
            <mat-form-field>
              <mat-label>Message:</mat-label>
              <input
                placeholder="Type Message Here..."
                matInput
                formControlName="message"
                
                type="string"
                required
              />
            </mat-form-field>
            <br />
            <mat-form-field>
              <mat-label>Message Date:</mat-label>
              <input
                placeholder="Type Message Here..."
                matInput
                formControlName="messageDateTime"
                
                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:

Data entered

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 },

CodePudding user response:

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');
}
  • Related