【问题标题】:How can I make document field = map in Firestore?如何在 Firestore 中制作文档字段 = 地图?
【发布时间】:2019-10-17 15:55:26
【问题描述】:

如何使文档字段 = map(object)?

我现在的代码,只是一个例子:


来自 html 输入的姓名、年龄和用户编号

在按钮上单击执行以下操作:

var nameInput
var ageInput
var userNumberInput
db.collection("users").doc("all_users").set({
 userNumberInput: {
  name: nameInput,
  age: ageInput
}
});

我的代码是这样做的:

collection --> document  --> field
users      --> all_users --> userNumberInput{name: kasper, age: 17} userNumberInput{name: caroline, age: 20}

我希望我的代码执行此操作,例如:

collection --> document  --> field
users      --> all_users --> user1{name: kasper, age: 17} user2{name: caroline, age: 20}

【问题讨论】:

  • 我很难理解你的问题。您的“user1”和“user2”字符串来自哪里?你是同时把它们都放进去吗?
  • @DougStevenson 是的,对不起。它来自 userNumberInput,因此在此示例中,用户只需编写“user1”或“user2”字符串。

标签: javascript firebase google-cloud-firestore


【解决方案1】:

我不确定我是否完全正确理解了您的问题,但我假设您希望变量“userNumberInput”的值作为键而不是实际的字符串“userNumberInput”

如果你使用 ES6,那么你可以使用 ComputedPropertyName 的特性。

var nameInput
var ageInput
var userNumberInput
db.collection("users").doc("all_users").set({
 [userNumberInput]: {
  name: nameInput,
  age: ageInput
}
});

如果没有,那么你可以用老式的方式来做

var nameInput
var ageInput
var userNumberInput
let obj = {}
obj[userNumberInput] = {
  name: nameInput,
  age: ageInput
}
db.collection("users").doc("all_users").set(obj);

【讨论】:

  • 是的,我也尝试过,但我写的 userNumberInput 没有 []。所以这就是我正在寻找的答案。因为当我执行我的代码时,它只是将映射字段名称设置为变量名称。所以谢谢,但是 [] 是做什么的? :)
  • 我现在已将我的代码作为您在此处给出的答案。它可以工作,但是当我通过我的 html 页面上的表单添加一个用户时,它就可以工作了。但是当我已经在(用户-> all_users-->)中拥有用户时。我通过表单添加了一个,它只是重写了(用户-> all_users->)下的已有用户。如何添加一个新的地图字段,而不是重写已经存在的用户?
  • 回复我自己的 2 条评论,firebase.google.com/docs/firestore/manage-data/… after .set({});添加 { 合并:真 } => .set({ }, { 合并:真 });
  • [] 是一个名为 Computed Property Name 的功能,developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
猜你喜欢
  • 1970-01-01
  • 2019-07-15
  • 2018-04-03
  • 1970-01-01
  • 2019-08-14
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多