Firestore:向db添加自定义对象

时间:2017-10-05 05:50:08

标签: angular firebase angularfire2 google-cloud-firestore

早上好,

我尝试从这个类中添加一个新创建的对象:

export class Sponsor implements ISponsor {

  title: string;    
  description?: string;
  creation: ICreation;

  constructor(title: string, description: string, author: string) {
     this.title = title;
     this.description = description;
     this.creation = new Creation(author);
  }
}

在我的服务中,create函数如下所示:

createSponsor(sponsor) {
   sponsor.id = this.afs.createId();
   return this.collection.doc(sponsor.id).set(sponsor);
}

当我这样尝试时,我收到以下错误:

  

FirebaseError:[code = invalid-argument]:函数DocumentReference.set()使用无效数据调用。数据必须是一个对象,但它是:一个自定义的赞助商对象

我该如何解决这个问题?

8 个答案:

答案 0 :(得分:23)

您也可以使用Object.assign({},赞助商)

所以在某种情况下它会是

this.collection.doc(sponsor.id).set(Object.assign({}, sponsor));

答案 1 :(得分:7)

您还可以将对象序列化为JSON并将其反序列化为常规JavaScript对象,如

this.collection.doc(sponsor.id).set(JSON.parse( JSON.stringify(sponsor)));

适用于深度嵌套。

答案 2 :(得分:3)

向Fabian Wiles致敬 - 我明白了!

  

虽然firebase可以将对象内部的数据发送到数据库,但是当数据返回时,它无法将其实例化回到类的实例中。因此不允许上课

只需保存这样的对象:

interface Person{
  name: string;
  age: number
}

var person: Person = { name: 'Toxicable', age: 22} ;

答案 3 :(得分:2)

对于我的解决方案,我有一个Interface

export interface Launch {
 id: string;
 date: Date;
 value: number;

}

const project = {}作为Launch;

this.db.collection( '发射')添加(项目);

答案 4 :(得分:1)

来自firebase的行为真的很奇怪。我是如何修复它的 - 通过创建新的接口并将转换方法添加到我的类中:

export class Happening {
 constructor(
  public date: EventDate,
  public participants: Array<string>,
  public title: string,
  public text: string,
  public uid?: string,
  public id?: string
 ){}

 public toDto = (): HappeningDto => {
  return {
    date: {
      year: this.date.year,
      month: this.date.month,
      day: this.date.day
    },
    participants: this.participants ? this.participants : [],
    title: this.title,
    text: this.text ? this.text : '',
    uid: this.uid,
    id: this.id ? this.id : null
  }
 }
}

export interface HappeningDto {
 date: {
  year: number,
  month: number,
  day: number
 },
 participants: Array<string>,
 title: string,
 text: string,
 uid?: string,
 id?: string
}

现在,我可以做到

add(event: Happening){
  event.uid = this.uid;
  this.$afs.collection<HappeningDto>('events').add(event.toDto())
    .then(
      (success) => console.log(success),
      (err) => console.warn(err)
    )
}

答案 5 :(得分:1)

Firestore不支持。但你可以使用https://github.com/typestack/class-transformer 它对我们来说非常好。

答案 6 :(得分:0)

如果使用Angular和AngularFire2,则可以使用AngularFirestype。 此模块旨在取代AngularFirestore,并允许使用自定义对象直接获取和设置数据到Firestore。

为此,需要3个步骤:

1.安装angular-firestype

`npm install angular-firestype --save`

2.使用映射对象

初始化AngularFirestype模块
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFirestypeModule, ModelType } from 'angular-firestype';
import { environment } from '../environments/environment';

import { User } from './user.ts';
import { Address } from './address.ts';
import { Message } from './message.ts';

/**
 * Definition of the app model mapping.
 * For more information, see https://github.com/bricepepin/angular-firestype#mapping-object.
 */
const model: {[key: string]: ModelType<any>} = {
  users: {
    type: User,
    arguments: ['username', 'image'],
    structure: {
      adress: Address
    },
    subcollections: {
      messages: Message
    }
  }
};

@NgModule({
 imports: [
   AngularFireModule.initializeApp(environment.firebase),
   AngularFireAuthModule,
   AngularFirestypeModule.forRoot(model),   // Import module using forRoot() to add mapping information
 ],
 declarations: [ AppComponent ],
 bootstrap: [ AppComponent ]
})
export class AppModule {}

3。注入AngularFirestype服务

import { Component } from '@angular/core';
import { AngularFirestype, Collection, Document } from 'angular-firestype';

import { User } from './user.ts';

@Component({
 selector: 'app-root',
 templateUrl: 'app.component.html',
 styleUrls: ['app.component.css']
})
export class AppComponent {
   const users: Observable<User[]>;
   const user: User;

   constructor(db: AngularFirestype) {
       const usersCollection: Collection<User> = db.collection<User>('users');
       usersCollection.valueChanges().subscribe(users => this.users = users);

       const userDoc: Document<User> = usersCollection.doc('user1');
       userDoc.valueChanges().subscribe(user => this.user = user);
       userDoc.set(this.user);
   }
}

您基本上可以像使用Angularfirestore一样使用AngularFirestype 有关详细信息,请参阅此处的主页:https://github.com/bricepepin/angular-firestype

答案 7 :(得分:0)

我在使用vue和nuxt时遇到类似的问题

firebase.firestore().collection('example')
   .doc()
   .set({
       'foo' : 'boo'
   })

错误:

Data must be an object, but it was: a custom Object object

This link helped me