从mat-select中将数据保存到数据库MongoDB [英] From mat-select save data to database MongoDB
问题描述
我有收藏玩家和收藏团队.我想向团队中添加负载球员.
I have collection Player and collection Teams. I want to add load players to teams.
在创建团队的HTML中,我从播放器加载数据,用户可以选择加载播放器:
in HTML in create Team, where I load data from players and user can choose load players:
<mat-form-field>
<mat-select placeholder="Goalkeepers" formControlName="goalkeeper">
<mat-option *ngFor="let player of goalkeepers" [value]="player">
{{player.name}} {{player.surename}} ({{player.price}}M)
</mat-option>
</mat-select>
<mat-error *ngIf="form.get('goalkeeper').invalid">Pleasse enter a goalkeeper.</mat-error>
</mat-form-field>
然后在user.component.ts中保存数据. 这是将播放器中的数据加载到HTML:
And in user.component.ts I save data. Here is load data from players to HTML:
this.playersService.getPlayersForTeam();
this.playersSub = this.playersService
.getPlayerUpdateListener()
.subscribe((playerData: {players: Player[]}) => {
this.players = playerData.players;
});
这是将数据保存到数据库:
And here is save data to database:
onSaveUserTeam() {
this.userTeamsService.addUserTeam(
this.form.value.name,
this.form.value.goalkeeper,
this.form.value.goalkeeper_sub,
this.form.value.midfielder1,
... etc ...
);
我没有错误地将数据发送到数据库.当我只有这个输入时:
I sent data to database without errors. When I had only this inputs:
<input matInput type="text" formControlName="goalkeeper" placeholder="UserTeam goalkeeper">
<mat-error *ngIf="form.get('goalkeeper').invalid">Please enter a userTeam goalkeeper.</mat-error>
</mat-form-field>
就像文本一样,当我写一些东西输入然后发送到数据库时,一切都很好.但是现在,当我从玩家集合中选择玩家进行垫选时,我会在数据库中得到如下内容:
So like text, when I write something to input and then send to database, all was good. But now, when I have mat-select with players from player collection, I get in database something like this:
{
_id: ObjectId('5c7ecdd75c09e23d903f1bb9')
name: "Test"
goalkeeper: "[object Object]"
goalkeeper_sub: "[object Object]"
}
这是一个问题,因为我需要具有相同的特定玩家详细信息,例如playerID,以便以后用于编辑团队等. 将数据保存到数据库中,我做错了什么? 谢谢您的帮助!
And it is a problem, because I need to have same specific player detail like playerID to use later for edit team etc... What I do wrong in seding data to database? Thanks for you help!
推荐答案
看起来Angular序列化对象的方式不像应该序列化的方式.也许您正在从表单中将错误的值传递给此方法.
It looks like Angular serializes objects not in a way it's supposed to serialize. Maybe you're passing incorrect values from your form to this method.
我建议您重构addUserTeam
方法,以便它可以接受需要上载的单个对象并完全删除表单数据.
I would suggest you to refactor addUserTeam
method so that it would accept a single object that needs to be uploaded and completely remove form data.
addUserTeam(userTeam: UserTeam) {
this.http.post('http://localhost:3000/api/userteams', userTeam);
}
UserTeam
是一个类/接口,其中包含屏幕快照中附加的所有属性.
Where UserTeam
is a class/interface that contains all the properties attached in the screenshot.
这篇关于从mat-select中将数据保存到数据库MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!