3

I have used Mean Stack to build a project. I have created a Report Form in which data can be inserted.

When I insert the data from the form the data is inserted to the collection.

But when I use Postman to insert data the data insertion fails.

Here are the code segments:

1.Front End Form - report.component.html

            <form (ngSubmit)="savereportdata()" novalidate>
            <ba-card>
                <div class="form-group">
                    <label for="middleItemId">Item ID</label>
                    <input type="text" class="form-control" placeholder="Enter Item ID" [(ngModel)]="itemId" name="itemId">
                </div>
                <div class="form-group">
                    <label for="middleItemName">Item Name</label>
                    <input type="text" class="form-control" placeholder="Enter Item Name" [(ngModel)]="itemName" name="itemName">
                </div>

                <div class="form-group">
                    <label for="warrentyUntil">Warrenty Until</label>
                    <input type="date" readonly="" class="form-control">
                </div>

                <div class="form-group">
                    <label for="reportDescription">Description</label>
                    <textarea class="form-control" rows="3" [(ngModel)]="reportDescription" name="reportDescription"></textarea>
                </div>

                <button type="submit" class="btn btn-primary">Submit</button>
            </ba-card>
        </form>

2.report.component.ts

import { NgModule,Component,Pipe,OnInit } from '@angular/core';
import { ReportItemService } from '../../../services/report-item.service'

@Component({
  selector: 'app-report',
  templateUrl: './report.component.html'
})

export class ReportComponent implements OnInit {

  itemId:Number;
  itemName:String;
  reportDescription:String;
  constructor(public reportservice:ReportItemService) {}

  ngOnInit() {}      

  savereportdata() {         
      const reportitem = {
          itemId:this.itemId,
          itemName:this.itemName,
          reportDescription:this.reportDescription
        };    
        this.reportservice.reportitemdata(reportitem).subscribe(res=> {
            console.log(res);
        }); 
    }
}  

3.report-item.service.ts

import { Injectable } from '@angular/core';
import { Http,Headers} from '@angular/http';
import 'rxjs/add/operator/map';


@Injectable()
export class ReportItemService {
    reportitem:any;
    constructor(private http:Http) {}
    reportitemdata(reportitem) {
        let headers=new Headers();
        headers.append('Content-Type','application/json');
        return this.http.post("http://localhost:3000/reportItem",reportitem,{headers:headers}).map(res=>res.json());
    }
} 

4.Backend Model - report.js

const mongoose = require('mongoose');
const schema = mongoose.Schema;

const reportSchema = new schema({
    itemId: { type: Number, required: true },
    itemName: { type: String },
    reportDescription: { type: String },
    date: { type: Date }
});

module.exports = mongoose.model("ReportItem", reportSchema);
module.exports.saveReportItem = function(newreport, callback) {
    console.log(newreport);
    newreport.save(callback);
};

5.router - reportItem.js

const express = require('express');
const router = express.Router();
const config = require('../config/database');
const ReportItem = require('../models/request-report/report');
router.post("", function(req, res) {

    const newreport = new ReportItem({
        itemId: req.body.itemId,
        itemName: req.body.itemName,
        reportDescription: req.body.reportDescription,
        date: new Date
    });

    ReportItem.saveReportItem(newreport, function(err, report) {
        if (err) {
            res.json({ state: false, msg: "data not inserted" });
        }
        if (report) {
            res.json({ state: true, msg: "data inserted" });
        }
    });
});

module.exports = router;

The Screenshot of the results when data is inserted from the form:

Data Inserted

The Screenshot of the Error in Postman:

Postman Data Insertion Failed

I've been trying to figure out this problem for weeks but couldn't.

Thanks loads in advance!

Serg
  • 2,346
  • 3
  • 29
  • 38
Gethma
  • 299
  • 1
  • 5
  • 24

1 Answers1

1

You could try using the bodyParser module in the js code to grab the data from the request. I’ve had issues with this in the past.

Danny Dainton
  • 23,069
  • 6
  • 67
  • 80
  • I have used the body parser module in app.js . The error is as follows now `ValidationError: ReportItem validation failed: itemId: Path `itemId` is required. at MongooseError.ValidationError.inspect (D:\inventory_api\node_modules\mongoose\lib\error\validation.js:57:23` – Gethma Dec 17 '17 at 08:29
  • Have you tried sending it through Postman as JSON rather than in a form? Using the `raw` option and `application/json` as the type. `{ itemId: 1, itemName: "A name" }` – Danny Dainton Dec 17 '17 at 08:35
  • Yes. still the state is failed. – Gethma Dec 17 '17 at 08:46
  • Sorry, not really sure I have anything else I can suggest. – Danny Dainton Dec 17 '17 at 09:01
  • What is returned in the console.log(newreport)? Is the request data coming back correctly? – Danny Dainton Dec 17 '17 at 09:10
  • now i edited the postman. i just removed the required field in my Modlel file. But postman show it has inserted the data. but when i check my collection nothing has been inserted. – Gethma Dec 17 '17 at 09:27
  • What is to console output of `report` on that if statement? Is it the correct set of data? – Danny Dainton Dec 17 '17 at 11:03
  • when i insert data for the console output is `(node:10456) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promis e library instead: http://mongoosejs.com/docs/promises.html { date: 2017-12-17T12:03:13.089Z, _id: 5a365d0190365e28d86bbab3 }` **it only inserts an empty field** – Gethma Dec 17 '17 at 12:05
  • Ok, but I still don’t think the data is being sent or picked up correctly via Postman. It looks like you create that `date` value in reportItem.js and that’s the only thing that’s making it through. – Danny Dainton Dec 17 '17 at 12:49