簡體   English   中英

從 Google Cloud Function 更新 Firestore 數據時,如何忽略未定義的值?

[英]How can I ignore undefined values when updating Firestore data from a Google Cloud Function?

在我的 index.js 文件中,我有:

const db = admin.firestore();
db.settings({ignoreUndefinedProperties:true});

在我的其他具有實際功能的 .js 文件中,我有:

const functions = require('firebase-functions');
const {Client, ReverseGeocodingLocationType, AddressType} = require("@googlemaps/google-maps-services-js");

async function addLocationData(addressComponents, reference){
    cityName = getLocationType(addressComponents, 'locality')
    stateName = getLocationType(addressComponents, 'administrative_area_level_1')
    countryName = getLocationType(addressComponents, 'country')
    await reference.set({
        'location.city': cityName,
        'location.state': stateName,
        'location.country': countryName
    },{ignoreUndefinedProperties:true})
    return true
}

但是,我仍然收到此錯誤:

參數“data”的值不是有效的 Firestore 文檔。 不能使用“未定義”作為 Firestore 值(在字段“ location.city ”中找到)。 如果要忽略未定義的值,請啟用ignoreUndefinedProperties

這種情況下的城市數據是未定義的,但我想忽略未定義的數據。

ignoreUndefinedProperties:true不是有效的 SetOption

SetOptions 參考: https ://firebase.google.com/docs/reference/js/v8/firebase.firestore.SetOptions

您可以通過merge: true並省略字段以保持它們不變。

您仍然需要更改代碼才能不傳遞未更改的密鑰。

async function addLocationData(addressComponents, reference){
    cityName = getLocationType(addressComponents, 'locality')
    stateName = getLocationType(addressComponents, 'administrative_area_level_1')
    countryName = getLocationType(addressComponents, 'country')
    const data = {}
    if (cityName != null) { 
      data['city.name'] = cityName;
    }
    // etc
    await reference.set(data, {merge: true})
    return true
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM