Firestore合并特定字段的数据

时间:2018-12-06 11:27:35

标签: google-cloud-firestore

  import { Component } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface Post{
	title: string;
	content: string;

}

interface PostId extends Post {
	id: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  postCollection: AngularFirestoreCollection<Post>;
  posts: any;
  title: [{}];
  content: string;
  name: string;
  number: string;
  postDoc: AngularFirestoreDocument<Post>;
  post: Observable<Post>;
  constructor(private afs: AngularFirestore){

  }

  ngOnInit(){
  	this.postCollection = this.afs.collection('posts');
  	//this.posts = this.postCollection.valueChanges();
  	//this.postCollection = this.afs.collection('posts', ref => ref.where('title', '==', 'Marvel'));
  	this.posts = this.postCollection.snapshotChanges().pipe(
  	    map(actions => {
  			return  actions.map(a => {
  				const data = a.payload.doc.data() as Post;
  				const id = a.payload.doc.id;
  				return {id, data};
   			})
  		})
    );
  }

  saveForm()
  {
    const name = this.name;
    const number = this.number;
  	const content = this.content;
    console.log(name,number,content);
  }

  resetForm()
  {
    this.name = '';
    this.number = '';
    this.content = '';
  }

  addPost()
  {
  this.afs.collection('posts').doc('my-custom-id')
    .set({ 
      'title': [{'name': this.name, 'number': this.number}],
      'content': this.content,
    },{ merge:true });

  	this.saveForm();
    this.resetForm();
  }

  getPost(postId){
  	this.postDoc = this.afs.doc('posts/' +postId);
  	this.post = this.postDoc.valueChanges();
  }

  deletePost(postId)
  {
  	this.afs.doc('posts/' +postId).delete();
  }
}
<input type="text" [(ngModel)] = "name" name="name" placeholder="name">
<input type="text" [(ngModel)] = "number" name="number" placeholder="number">
<textarea [(ngModel)] = "content" name="content" placeholder="content"></textarea>
<input type="submit" value="submit-to-firestore" (click)="addPost()"> 

<ul *ngFor = "let post of posts | async">
  <li (click)="getPost(post.id)">
    <strong>{{ post.data.name }}(<a href ="#" (click)="deletePost(post.id)">Delete</a>)</strong>
    <br />
    {{ post.data.number }}
    {{ post.data.content }}
  </li>
</ul>

<h1> A specific Post: </h1>

<h3> {{ (post | async)?.name }}</h3>
<p> {{ (post | async)?.content }}</p>

我有一个类似于以下内容的firestore数据库结构:

field1 : value,  
field : [{field2: value,  field3:value}]

我想要的是合并数据,如下所示:

field1: value,   
field : [{field2: value1,  field3:value1}
        [{field2:value,field3:value}]

我该如何实现?

我已经尝试使用{merge:true}进行设置。

我也尝试过更新,但数据已被覆盖。 我想要的是title数组应该以唯一的ID逐一添加数据。

例如 docid1 ---> title[0]

docid2 ----> title[0,1] 等等

0 个答案:

没有答案