【问题标题】:How to get users document id in Firestore using Javascript?如何使用 Javascript 在 Firestore 中获取用户文档 ID?
【发布时间】:2021-08-02 19:46:33
【问题描述】:

如何仅获取 Firestore 中的最后一个文档 ID?

我试过了

                    auth.onAuthStateChanged(user => {
                //set document from firestore
                    var date=new Date();  
                    var day=date.getDate();  
                    var month=date.getMonth()+1;  
                    var year=date.getFullYear(); 
                    if (user){
                        db.collection('users').doc(user.uid).collection('orders').doc().set({
                            things:cart,
                            orderState: "Order pending",
                            date:day+'/'+month+'/'+year,    
                        })
                        //get document from firestore
             db.collection('users').doc(user.uid).collection('orders').doc().get()
             .then(snapshot => console.log(snapshot.id))
     })

结果我得到了错误的 id 那不在订单文档中!!

这是我的文件:

【问题讨论】:

  • 你能解释一下你指的是什么顺序吗?
  • 我想获取新的订单 ID,但是当我调用订单 ID 时遇到的问题是错误的 ID,您可以检查 Firestore 中的最后一个订单 ID 是 (sRUMtGcX50BjmvOVAaoF),但是当我在控制台工具中调用它的到来(BfoJBL0sSsYQesbbSXP0)不同的 ids

标签: javascript firebase google-cloud-firestore


【解决方案1】:

您正在运行 db.collection('users').doc(user.uid).collection('orders').doc() 两次,这会创建 2 个不同的 DocumentReferences,因此它们是不同的。如果您正在尝试获取刚刚添加的文档,请尝试以下操作:

if (user) {
  db.collection('users').doc(user.uid).collection('orders').doc().set({
    things:cart,
    orderState: "Order pending",
    date:day+'/'+month+'/'+year,    
  }).then((ref) => {
    console.log(ref.id)
    // ref.get() get document
  })  
}   
const ref = db.collection('users').doc(user.uid).collection('orders').doc()
console.log("Doc ID:", ref.id)
ref.set({...data}).then((snapshot) => {
  console.log(`Document ${snapshot.id} added`)
  // This ID will be same as ref.id
})

【讨论】:

猜你喜欢
  • 2021-07-17
  • 2022-07-21
  • 2018-10-15
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 2020-12-16
  • 2022-10-06
相关资源
最近更新 更多