在Cloud Firestore中创建或更新Firebase

时间:2018-10-24 09:07:30

标签: firebase google-cloud-firestore

我正在开发一个简单的应用程序,并对Firebase Cloud Firestore存有疑问。

当我们在代码中执行db.doc('docname').set(myInfo)时,Firebase会将其视为“创建”还是“更新”?

2 个答案:

答案 0 :(得分:4)

如果您仅使用set()函数来简单,则意味着如果该文档不存在,则会创建该文档。这意味着您需要为写入操作付费。如果文档确实存在,则除非您指定将数据合并到现有文档中,否则它将用新提供的数据覆盖其内容,如下所示:

var setWithMerge = yourDocRef.set({
  yourProperty: "NewValue"
}, { merge: true });

这还将代表写操作,并且还会向您收费。如果要按以下代码更新属性:

return yourDocRef.update({
    yourProperty: "NewValue"
})
.then(function() {
    console.log("Document successfully updated!");
})
.catch(function(error) {
    console.error("Error updating document: ", error);
});

这也意味着您正在执行写操作。根据有关Firestoee usage and limits的官方文档,写操作和更新操作之间没有区别,两者都被视为写操作。

答案 1 :(得分:0)

设置等于创建一个新文档:

import { Component } from '@angular/core';

import { Directive, Input, forwardRef } from "@angular/core";
import {
    Validator, AbstractControl, NG_VALIDATORS, Validators, ValidatorFn
    } from "@angular/forms";

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  hero: any = {};
}


@Directive({
    selector: "[min][formControlName],[min][formControl],[min][ngModel]",
    providers: [
        { provide: NG_VALIDATORS,
            useExisting: forwardRef(() => MinDirective),
            multi: true }
    ]
})
export class MinDirective implements Validator {
    private _validator: ValidatorFn;
    @Input() public set min(value: string) {
        this._validator = Validators.min(parseInt(value, 10));
    }

    public validate(control: AbstractControl): { [key: string]: any } {
        return this._validator(control);
    }
}

@Directive({
    selector: "[max][formControlName],[max][formControl],[max][ngModel]",
    providers: [
        { provide: NG_VALIDATORS,
            useExisting: forwardRef(() => MaxDirective),
            multi: true }
    ]
})
export class MaxDirective implements Validator {
    private _validator: ValidatorFn;
    @Input() public set max(value: string) {
        this._validator = Validators.max(parseInt(value, 10));
    }

    public validate(control: AbstractControl): { [key: string]: any } {
        return this._validator(control);
    }
}

<input type="number" [(ngModel)]="hero.count" name="count" #count="ngModel" required min="1" max="100">

<p *ngIf="count.invalid">Invalid Published Year</p>

将使用以下属性创建一个名为LA的新文档。 或者,如果您不想指定ID并希望Firestore为您设置自动唯一ID:

// Add a new document in collection "cities"
db.collection("cities").doc("LA").set({
    name: "Los Angeles",
    state: "CA",
    country: "USA"
})

更新在Firestore中具有自己的功能:

db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})

More examples and explanation