How to write to mongodb via API

Asked

Viewed 71 times

1

I have this API(Controller)

[Produces("application/json")]
[Route("api/[controller]")]
public class TypesFieldsController : Controller
{
        private IAddTypeFieldService addTypeFieldService;

        public TypesFieldsController(IAddTypeFieldService addTypeFieldService)
        {
            this.addTypeFieldService = addTypeFieldService;
        }

        //[Authorize("Bearer")]
        [AllowAnonymous]
        [HttpPost (Name ="PostTypeField")]
        public async Task<IActionResult> PostTypeField([FromBody] TypeFieldRequest typeFieldRequest)
        {
            AddTypeFieldCommand addTypeFieldCommand = new AddTypeFieldCommand(typeFieldRequest.Name);
            AddTypeFieldResult addTypeFieldResult = await this.addTypeFieldService.Process(addTypeFieldCommand);

            TypesFieldsDetailsModel typesFieldsDetailsModel = new TypesFieldsDetailsModel(addTypeFieldResult.TypeField.TypeFieldId, addTypeFieldResult.TypeField.Name);

            return new ObjectResult(typesFieldsDetailsModel);
        }

    }

And also this model

public class TypeField : Entity, IAggregateRoot
    {
        public string Name { get; private set; }

        public int Version { get; set; }

        public TypeField(string name)
        {
            this.Name = name;
        }
    }

Well, what I need now would be to take my form HTML and record in Mongo. This is mine HTML and the send button. This is why I must give the POST.

<div class="container">
  <form role="form" style="width:400px; margin: 0 auto;">
    <h1>Types Fields</h1>

    <div></div>

    <div class="required-field-block">
        <input type="text" placeholder="Nome" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>

    <div class="required-field-block">
        <input type="text" placeholder="Versão" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>

    <button class="btn btn-primary">Criar</button>
</form>
</div> 

And this here is the method ADD of my service. I just don’t understand where it comes from Itemname and how I pass a form whole.

public add<T>(itemName: string): Observable<T> {
    const toAdd = JSON.stringify({ ItemName: itemName  });

    return this.http.post<T>(this.actionUrl, toAdd);
}

How I give a post with the html above using Angular 6?

EDIT1 I did this: Component

export class CreateTypeFieldsComponent implements OnInit {

  private _createTypesFields: Model.CreateTypesFields;
  private form: FormGroup;

  constructor(private _createTypeService: CreateTypeFieldsService, private builder: FormBuilder) {

  }      

  ngOnInit() {

      this._createTypeService.postCreateTypeFields(this._createTypesFields)
      .subscribe( success => {
        if(success.Result){
          //anything here
        }
      },
      error =>{
      }
    );

    this.form = this.builder.group({
      nome: '',
      versao: ''
    }) 
  }

and in html I have this

<div class="container">
  <form [formGroup]="form" (ngSubmit)="add(form.value)" role="form" style="width:400px; margin: 0 auto;">
    <h1>Types Fields</h1>

    <div class="required-field-block">
        <input formControlName="nome" type="text" placeholder="Nome" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>

    <div class="required-field-block">
        <input formControlName="versao" type="text" placeholder="Versão" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>    
    <button type="submit" class="btn btn-primary" >Criar</button>
</form>
</div>

when I run I get this error, while debugging in browser:

Can’t bind to 'formGroup' Since it isn’t a known Property of 'form'. (" ][formGroup]="form" (ngSubmit)=" add(form.value)" role="form" style="width:400px; margin: 0 auto;"> "): ng://Appmodule/Createtypefieldscomponent.html@1:8 No Provider for Controlcontainer (" [ERROR ->]

EDIT2

Well, with the help of the colleagues below, I managed to fix the mistakes, but it still doesn’t record, but the Insert in Mongodb is called, because the ID(GUID in Monodb) is generated each time I press the Create button. It happens, that the field Name comes empty and I think it has to do with the form I am sending. Below follows the changes I made and with that I eliminated the errors: Component

import { Component, OnInit, ModuleWithProviders } from '@angular/core';
import { FormControl,FormBuilder, FormGroup, NgControl } from '@angular/forms';
import { CreateTypeFieldsService } from '../create-type-fields.service';

@Component({
  selector: 'app-create-type-fields',
  templateUrl: './create-type-fields.component.html',
  styleUrls: ['./create-type-fields.component.css'],
  providers: []
})
export class CreateTypeFieldsComponent implements OnInit {

  createForm = new FormGroup({
    Name: new FormControl
  })

  private _createTypesFields: Model.CreateTypesFields;
  private form: FormGroup;

  constructor(private _createTypeService: CreateTypeFieldsService, private builder: FormBuilder) { 

     this.form = this.builder.group({
      Name: ''
    }) 
  } 
  ngOnInit() { }

    onPostCreateTypeFields(){
      this.createForm.value;
      this._createTypeService.postCreateTypeFields(this._createTypesFields)
          .subscribe( success => {
            if(success.Result){
              //anything here
            }
          },
          error =>{
          }
        );
      }
    }

Service

import { Injectable } from '@angular/core';
import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Configuration } from './app.constants';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class CreateTypeFieldsService {

  private actionUrl: string;
  private url: 'http://localhost:56758/api';

  constructor(private http: HttpClient, private _configuration: Configuration) { 
    this.actionUrl = _configuration.ServerWithApiUrl + 'TypesFields/';
  }

    public postCreateTypeFields(itemName: Model.CreateTypesFields): Observable<any> {

      const toAdd = JSON.stringify({ ItemName: itemName });

      return this.http.post(this.actionUrl, toAdd, httpOptions);
  }
}

HTML

<div class="container">
  <form [formGroup]="createForm" (ngSubmit)="onPostCreateTypeFields()" style="width:400px; margin: 0 auto;">
    <h1>Types Fields</h1>

    <div class="required-field-block">
        <input formControlName="Name" type="text" placeholder="Nome" class="form-control">
        <div class="required-icon">
            <div class="text">*</div>
        </div>
    </div>
    <button type="submit" class="btn btn-primary" >Criar</button>
</form>
</div>

When I write(create) the Name field comes null in Mongodb. See below Postman

{
    "error": false,
    "itens": [
       {
            "typeFieldId": "0faca34a-8a52-4f03-911a-cedc6f3e7b0c",
            "name": null
        },
        {
            "typeFieldId": "a074125d-4fe0-429b-a811-d148881e8036",
            "name": null
        },
        {
            "typeFieldId": "880dc3e6-38d0-44ad-b261-7da50b593fb6",
            "name": null
        },
        {
            "typeFieldId": "90211c1e-298e-4919-a043-2ee45885e7aa",
            "name": null
        },
        {
            "typeFieldId": "19261221-e822-498d-9265-a51fc69224a8",
            "name": null
        },
        {
            "typeFieldId": "8b19100e-07ef-4fff-8053-7475ffeb4325",
            "name": null
        },
        {
            "typeFieldId": "a4f4fbf5-737c-4089-bdb1-649599a9be6e",
            "name": null
        },
        {
            "typeFieldId": "b5746f34-28b0-4e17-8ab9-13113632d942",
            "name": null
        },
        {
            "typeFieldId": "d5a21f36-a33c-46cc-961d-edd1c1fc76aa",
            "name": null
        },
        {
            "typeFieldId": "075a556c-8633-43aa-9ee8-0aa955c85229",
            "name": null
        },
        {
            "typeFieldId": "c48c9287-26c5-4e88-8dcc-3129ba241122",
            "name": null
        },
        {
            "typeFieldId": "746252ae-d72a-4bbb-ac6a-a72aff9dcf55",
            "name": null
        },
        {
            "typeFieldId": "2c5e6e2b-9df4-4077-8dba-561479b929e5",
            "name": null
        },
        {
            "typeFieldId": "9723de60-8172-47f9-baa9-d4ba25ba5bad",
            "name": null
        },
        {
            "typeFieldId": "d2ce0c2d-f352-4007-bbcf-92ed3236ddc0",
            "name": null
        },
        {
            "typeFieldId": "294f3233-2fbe-4e25-818e-fed5336d5a28",
            "name": null
        },
        {
            "typeFieldId": "e19e6dbf-ac96-4170-8e80-5a0fac28c924",
            "name": null
        },
        {
            "typeFieldId": "401c6eb1-8876-4b34-b847-709c3a956dee",
            "name": null
        },
        {
            "typeFieldId": "bd851785-1f37-48ca-8bbe-5f34eb29ba13",
            "name": null
        },
        {
            "typeFieldId": "b3f628bf-9bcb-4b55-9cbb-aab18f64e72d",
            "name": null
        }
    ],
    "message": ""
}

EDIT3

Well, my service was like this:

public postCreateTypeFields(itemName: Model.CreateTypesFields): Observable<any> {
   return this.http.post(this.actionUrl, itemName, httpOptions);
}

and changed the Name property to name, actually looking at the API by Swagger, he expected a name and not Name, the problem is that by Postman he accepted Name instead of name. Ok

  • @Lucasbrogni, the html I passed above is my form

  • I passed on the answer. The solution for your case is the use of the reactive Forms. https://angular.io/guide/reactive-forms Have a look at the documentation if you are in doubt.

  • @Lucasbrogni, I made an issue in the post(Edit2) and there I inform what is happening

  • your API expects to receive the Main Name ?

  • Yes, public Guid Id { get; private set; }&#xA; public string Name { get; private set; }&#xA;&#xA; public AddTypeFieldCommand(string name)&#xA; {&#xA; this.Name = name;&#xA; }

  • The network output is going data?

  • Apparently so

  • Debugging the Component in the browser, I have value here: this.createForm.value, I have exactly what is in the input, but here I have doubt, in this line this. _createTypesFields, because in the debug I have Undefined

Show 4 more comments

2 answers

1

It seems you forgot to import the reactive FormsModule where you declare your component.

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ReactiveFormsModule 
  ],
  declarations:[
      seuComponente
   ]
  • That’s right, but I had already solved it.

  • I made an edit in the post(Edit2) and there I inform what is happening

  • tries to see if in the network tab you are sending in the same way you send in Postman. In Postman the request works?

  • Yes, in Postman I can record and recover. How do I see in the network tab? What do I see there?

  • Just press F12 and select network. Then send the form and see if the request is the same way you send it to Postman.

  • I made an issue in the post (Edit3) and put there the solution.

Show 1 more comment

1

In your case the itemName you are only receiving a string, so it will not be the whole form.

Create a formGroup as follows:

  <form [formGroup]="form" (ngSubmit)="add(form.value)" role="form" style="width:400px; margin: 0 auto;">
    <h1>Types Fields</h1>

In typescript make the form as follows:

constructor(private builder: FormBuilder)
form: FormGroup;

 this.form = this.builder.group({
      nome: '',
      versao: ''
})

And later add to your inputs:

<input formControlName="versao" type="text" placeholder="Versão" class="form-control">
<input formControlName="nome" type="text" placeholder="Nome" class="form-control">

After this within your post can be done as follows:

public add<T>(itemName: any): Observable<T> {
    const toAdd = JSON.stringify(itemName);

    return this.http.post<T>(this.actionUrl, toAdd);
}
  • When commenting the container div I have this: Can't bind to 'formGroup' since it isn't a known property of 'form'. ("<!-- <div class="container"> -->&#xA; <form [ERROR ->][formGroup]="form" (ngSubmit)="add(form.value)" role="form" style="width:400px; margin: 0 auto;">&#xA; "): ng:///AppModule/CreateTypeFieldsComponent.html@1:8&#xA;No provider for ControlContainer ("<!-- <div class="container"> -->

  • If no comment gives this error: Can't bind to 'formGroup' since it isn't a known property of 'form'. ("<div class="container">&#xA; <form [ERROR ->][formGroup]="form" (ngSubmit)="add(form.value)" role="form" style="width:400px; margin: 0 auto;">&#xA; "): ng:///AppModule/CreateTypeFieldsComponent.html@1:8&#xA;No provider for ControlContainer ("<div class="container">

  • Even create the form in typescript ?

  • This typescript you say is my Service or my Component?

  • Component, inside the Component injects formBuilder dependency into the constructor and instantiates a form equal to the one I passed. You may need to make some adjustments to the q passed code in relation to the method that is called or something. I recommend reading the documentation for a better understanding, if applicable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.