简体   繁体   English

如何在 Firestore 的父 map 字段中添加新的 map 字段?

[英]How to add a new map field inside a parent map field in Firestore?

I want to add a new map field inside another map field.我想在另一个 map 字段中添加一个新的 map 字段。 My data structure looks like this:我的数据结构如下所示: 在此处输入图像描述

I want to add a 'field b' after 'field a' inside 'Filed 1' (pardon my typo).我想在“Filed 1”中的“field a”之后添加一个“field b”(请原谅我的打字错误)。

my code looks like this我的代码看起来像这样

 const collsRef = doc(db, "collections", collectionUid); // get the right document
 await setDoc(collsRef, { sellectData }, { merge: true });

but not only this is giving me an error, I believe this code would only add a new field at the same level as 'Filed 1'但这不仅给我一个错误,我相信这段代码只会在与“归档 1”相同的级别添加一个新字段

在此处输入图像描述

the data type triggering the unsupported field value error is an JS object like so – do I need to parse it before comiting it to the db?触发不受支持的字段值错误的数据类型是 JS object 就像这样——我需要在将它提交给数据库之前解析它吗?

在此处输入图像描述

I've blanked out data and left the structure and syntax because it contained personal sensitive data.我删除了数据并保留了结构和语法,因为它包含个人敏感数据。 I hope it's enough to explain the problem.我希望这足以解释问题。

many thanks in advance提前谢谢了

I'm not sure what the sellectData structure looks like but you have to construct an object that has the same structure from Firestore.我不确定sellectData结构是什么样的,但您必须构建一个 object,它与 Firestore 具有相同的结构。 See sample code below:请参阅下面的示例代码:

const collsRef = doc(db, "collections", collectionUid);

let sellectData = {
  "field b": { "key b" : "value b" }
}

await setDoc(collsRef, { 
  "Filed 1": sellectData
}, { merge: true });

This would result in (already corrected your typo):这将导致(已更正您的拼写错误): 在此处输入图像描述


Update:更新:

You have two options to set the object key as a variable.您有两个选项可以将 object 键设置为变量。

You need to make the object first, then use [] to set it.:您需要先制作object,然后使用[]设置它。:

let key = "Field 1";
let sellectData = {
  "field b": { "key b" : "value b" }
}

await setDoc(collsRef, {
  [key]: sellectData
}, { merge: true });

Or, by contructing the object itself.或者,通过构建 object 本身。

let key = "Field 1";

let sellectData = {
  [key] : { "field b": 
    { "key b" : "value b" }
  }
}

// Remove the curly brackets `{}` in this case.
await setDoc(collsRef, 
  sellectData, 
  { merge: true });

For more information, see Update fields in nested objects .有关详细信息,请参阅更新嵌套对象中的字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM