如何将Firebase每个文档中的指定字段添加到列表中?
将Firebase文档字段值添加到列表的实现示例
下面针对不同开发平台,给出具体的代码实现,假设你已经能正常获取Firebase Firestore的文档实例:
Web(JavaScript/TypeScript)
// 初始化空列表存储字段值 const fieldValues = []; // 获取目标文档 firebase.firestore().collection('your-collection').doc('your-doc-id').get() .then(doc => { if (doc.exists) { const docData = doc.data(); // 方式1:逐个添加指定字段 fieldValues.push(docData.name); fieldValues.push(docData.email); fieldValues.push(docData.age); // 方式2:批量遍历字段名数组(更适合多字段场景) const targetFields = ['name', 'email', 'age']; targetFields.forEach(field => { // 可选:判断字段是否存在,避免添加undefined if (docData[field] !== undefined) { fieldValues.push(docData[field]); } }); console.log('最终字段值列表:', fieldValues); } else { console.log('目标文档不存在'); } }) .catch(err => console.error('获取文档出错:', err));
Android(Kotlin)
// 初始化可变列表存储字段值 val fieldValues = mutableListOf<Any>() // 获取目标文档 FirebaseFirestore.getInstance() .collection("your-collection") .document("your-doc-id") .get() .addOnSuccessListener { document -> if (document.exists()) { val targetFields = listOf("name", "email", "age") targetFields.forEach { field -> // 字段存在时才添加到列表 document.get(field)?.let { fieldValues.add(it) } } Log.d("FirebaseDemo", "字段值列表: $fieldValues") } else { Log.d("FirebaseDemo", "目标文档不存在") } } .addOnFailureListener { e -> Log.w("FirebaseDemo", "获取文档失败", e) }
iOS(Swift)
// 初始化空列表存储字段值 var fieldValues: [Any] = [] // 获取目标文档 Firestore.firestore().collection("your-collection").document("your-doc-id").getDocument { document, error in guard let document = document, document.exists, error == nil else { print(error?.localizedDescription ?? "目标文档不存在") return } let targetFields = ["name", "email", "age"] for field in targetFields { if let value = document.data()?[field] { fieldValues.append(value) } } print("字段值列表: \(fieldValues)") }
补充说明
- 如果需要处理集合中多个文档的字段,只需在查询集合的循环逻辑中,对每个文档重复上述字段提取并添加到列表的操作即可。
- 建议添加字段存在性判断,避免将
null或undefined值加入列表,保证数据整洁。
内容的提问来源于stack exchange,提问作者pika3113
相关产品推荐
相关产品推荐

