如何在Firestore中的嵌套文档中更新嵌套文档?

时间:2020-03-12 00:32:08

标签: firebase flutter dart google-cloud-firestore google-cloud-functions

这是我的职能

exports.updateUserSettings = functions.https.onRequest((request, response) => {
  cors(request, response, () => {
    setResponseHeaders(response);
    console.log('input', request.body);
    const name = request.body.name;
    const settings = request.body.settings;

     return db
      .collection(COLLECTION_USERS)
      .doc(name)
      .update(settings)
      .then(() => {
        return response.status(200).json({
          success: true,
          data: null
        });
      })
      .catch(error => {
        return response.status(200).json({
          success: false,
          error: error,
          data: null
        });
      });
  });
});

这是我的Firestore文档enter image description here

我想更新我的设置对象。这是我的请求正文

 { name: 'frank6',
   settings: '{"autoPass":true,
   "autoRoll":true,
   "colors": {
     "check":"#000000", 
     "dark":"#b58863", 
     "light":"#f0d9b5", 
     "mate":"#ff4500", 
     "selected":"#90ee90", 
     "source":"#90ee90", 
     "target":"#228b22"
    }, 
   "language":"en",
   "showCheckMoves":true,
   "showFileRank":true,
   "showLastOpponentMove":true,
   "showMateMoves":true,
   "showMoves":true,
   "sounds":true,
   "view":"2D"
   }' 
 }

它有一个错误错误:参数“ data”的值不是有效的Firestore文档。输入不是普通的JavaScript对象。我知道如何基于https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects更新嵌套文档,但是我不确定为什么会发生此错误,也许我需要格式化我的请求正文,但现在确定如何。

我也收到了我的Flutter Dart网络应用程序的请求

Future<void> updateUserSettings(ChexiUser user) async {
  await http.post(CLOUD_FUNCTIONS_BASE_URL + '/updateUserSettings', body: {
    'name': user.name,
    'settings': convert.jsonEncode(user.toSettingsFirebaseDocument())
  });
}

这是我的toSettingsFirebaseDocument函数

Map<String, dynamic> toSettingsFirebaseDocument() {
  return {
    'autoPass': settingsAutoPass,
    'autoRoll': settingsAutoRoll,
    'colors': {
      'check': settingsColorsCheck,
      'dark': settingsColorsDark,
      'light': settingsColorsLight,
      'mate': settingsColorsMate,
      'selected': settingsColorsSelected,
      'source': settingsColorsSource,
      'target': settingsColorsTarget
    },
    'language': settingsLanguage,
    'showCheckMoves': settingsShowCheckMoves,
    'showFileRank': settingsShowFileRank,
    'showLastOpponentMove': settingsShowLastOpponentMove,
    'showMateMoves': settingsShowMateMoves,
    'showMoves': settingsShowMoves,
    'sounds': settingsSounds,
    'view': settingsView
  };
  }
 }

1 个答案:

答案 0 :(得分:3)

好吧,事实证明这只是一个简单的错误。我只需要用JSON.parse()包装我的request.body

const settings = JSON.parse(request.body.settings);

它正常工作。我不会删除这个问题,也许它将对遇到类似问题的其他人有用。