使用react native(javascript)在firestore中进行文档引用

使用react native(javascript)在firestore中进行文档引用,javascript,firebase,react-native,google-cloud-firestore,Javascript,Firebase,React Native,Google Cloud Firestore,文档引用用于从firestore获取文档字段及其集合。以下是一些例子: 1。从具有docRef的字段读取数据的函数 [Firestore架构]: 在集合people中有doc名为user1,其中有一个名为hlpr的字段,其中有user2的docRef,因此如果我想访问docRef数据,我将使用以下代码: function foo4() { var user1 = db.collection('people').doc('user1') user1.get().then((data) =>

文档引用用于从firestore获取文档字段及其集合。以下是一些例子:

1。从具有docRef的字段读取数据的函数 [Firestore架构]: 在集合people中有doc名为user1,其中有一个名为hlpr的字段,其中有user2的docRef,因此如果我想访问docRef数据,我将使用以下代码:

function foo4() {
var user1 = db.collection('people').doc('user1') 
user1.get().then((data) => {         //get user1 whole doc using get()
  var t = data.get('hlpr')           //choose field 'hlpr'
  t.get().then((doc) => {            //get 'hlpr' data() from get()
    var user2 = doc.data()           //get whole doc from user2
    console.log(user2.name)          //output field 'name' from user 2
  })
})}
2。从docRef的数组中读取数据。在前面的图像中,您可以看到名为“cts”的字段,该字段具有docRef数组。代码:

function foo3() { //function to get data from array of docRef
var user1 = db.collection('people').doc('user1'); //choose user1 doc
user1.get().then((doc) => {                //get data() of user1 using get()
  var contacts = doc.get('cts');                //set var k to field 'cts'
  contacts.forEach((data) => {                  //for each item in array field cts
    var userx = data.get();                 //read data() using get()
    userx.then((doc) => {                   
      var frnd = doc.data();              //set frnd to each data we get from doc
      console.log(frnd.name)              //output their any field value here i have chosen name
    });
  });
})}

注意:上面的代码工作正常,您也可以使用数据放入数组。上面的代码可能不是获取数据的最佳方法,但我是初学者,所以这是我能做的最好的方法。

您可以根据注释将代码分解为一个等待链,但如果处理一个项目可以相当干净,则是一个承诺链

异步函数foo4(){ var user2=await db.collection('people').doc('user1').get() .then(data=>data.get('hlpr')) .then(doc=>doc.data()) .finally(result=>result) .catch(console.log()); 在嵌套承诺链时,可以执行一些干净的代码


第二个代码块有潜在的错误,如果您的客户端超过了挂起的50个文档,客户端模块将抛出错误并导致读取失败。

您试图实现的是什么,哪些不按预期工作?是否有更好的方法来执行这些操作?因为有时我会对太多嵌套代码感到非常困惑,您可以切换使用
异步等待
语句。