如何在Firestore中将数据更新/推送到空数组-Firebase

时间:2019-07-16 09:09:20

标签: firebase google-cloud-firestore

我正在使用React和Firestore。注册用户后,我在其个人资料上保存了一个空数组 try { File dir = Environment.getExternalStorageDirectory(); File yourFile = new File(Environment.getExternalStorageDirectory() + "/" + "mybits/file.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(yourFile); Element element = doc.getDocumentElement(); element.normalize(); NodeList nList = doc.getElementsByTagName("employee"); NodeList nList1 = doc.getElementsByTagName("cost"); for (int i = 0; i < nList.getLength(); i++) { Node node = nList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element2 = (Element) node; tv1.setText(tv1.getText() + "Name : " + getValue("name", element2) + "\n"); tv1.setText(tv1.getText() + "Surname : " + getValue("surname", element2) + "\n"); for (int j = 0; j < nList1.getLength(); j++) { Node node1 = nList1.item(j); if (node1.getNodeType() == Node.ELEMENT_NODE) { Element element3 = (Element) node1; tv1.setText(tv1.getText() + "Salary : £" + getValue("salary", element3) + "\n"); Salary = Integer.parseInt(getValue("salary", element3)); } } tv1.setText(tv1.getText() + "-----------------------\n"); name = getValue("name", element2); Surname = getValue("surname", element2); myDB.execSQL("INSERT INTO TestDB VALUES('" + name + "','" + Surname + "'," + Salary + ")"); } } } catch (Exception e) { e.printStackTrace(); } } private static String getValue(String tag, Element element) { NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes(); Node node = nodeList.item(0); return node.getNodeValue(); } 。当一个用户向另一个用户撰写消息时,在此期间,我想将一些数据推送到此{chats : []}数组中。应该记住一件事,这个特定的数组不应该被覆盖。简而言之,应该将新的价值推给它。

我所能做的就是

chats

注意:我的方法将覆盖整个数组的数据。

Firestore用户数据示例

db.collection('Users').doc(userid).update({
  chats: ['somevalue']
})

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了,我认为这是实现它的最简单方法。您可以通过评论了解它的工作原理。

我所做的只是:

  1. chats[]对象获取Users数组
  2. 将新值推入检索到的数组
  3. 使用推送到其中的新更新值来更新chats[]数组。

//Get the Following Users through the specific document ID
Promise.all([
  db.collection('Users').doc(new Cookies().getCookie('uid')).get(),
  db.collection('Users').doc(this.props.data['0'].userId).get()
]).then(e => {
  //Get the Chats array from the object
  let c = e.map(lists => lists.data().chats)
  //push new values which is 'loc' in my case to the Chats arrays
  c.forEach(e => {
    e.push(loc)
  })

  //Make two Other promises to update the chat arrays with the upated values.
  Promise.all([
    db.collection('Users').doc(new Cookies().getCookie('uid')).update({
      chats: c[0]
    }),
    db.collection('Users').doc(this.props.data['0'].userId).update({
      chats: c[1]
    }),
  ]).then(e => {
    console.log("Docments Updated")
  })

})