如何将Firestore文档ID存入IdCrucero?字段为空问题排查
问题原因
你当前的代码逻辑是先提交数据到Firestore,再获取文档ID,导致写入Firestore的obj里的idCrucero是传入的空值(因为文档ID是addDoc执行后才生成的)。虽然之后你把docRef.id赋值给了this.idCrucero并能打印出来,但这时候数据已经写入Firestore,无法回溯修改之前的字段。
解决方案
推荐两种修复方式,优先选第一种(仅1次写操作,性能更优):
方案一:提前生成文档ID,一次性写入
先通过doc()生成带随机ID的文档引用,再把ID放入数据对象中,最后用setDoc写入:
async guardarCrucero( // 移除原idCrucero参数,因为我们要使用Firestore自动生成的ID name: any, subtitle: any, imagenCrucero: any, descripcion: any, imagenDescripcion: any, tituloQueHacer: any[], imagenQueHacer: any[], descripcionQueHacer: any[], tituloCamarotes: any[], descripcionCamarotes: any[], imagenCamarotes: any[], planos: any[], lugares: any[], precioLugares: any[], puertos: any[] ) { // 生成带随机ID的文档引用 const crucerosRef = collection(this.firestore, 'Cruceros'); const newDocRef = doc(crucerosRef); const newId = newDocRef.id; this.idCrucero = newId; const obj ={ "idCrucero" : newId, // 直接使用提前生成的文档ID "name" : name, "subtitle" : subtitle, "imagenCrucero" : imagenCrucero, "descripcion" : descripcion, "imagenDescripcion" : imagenDescripcion, "tituloQueHacer" : tituloQueHacer, "imagenQueHacer" : imagenQueHacer, "descripcionQueHacer" : descripcionQueHacer, "tituloCamarotes" : tituloCamarotes, "descripcionCamarotes" : descripcionCamarotes, "imagenCamarotes" : imagenCamarotes, "planos" : planos, "lugares": lugares, "precioLugares": precioLugares, "puertos": puertos }; // 一次性写入完整数据 await setDoc(newDocRef, obj); console.log(this.idCrucero); }
方案二:先写入数据,再补充更新ID(适合最小化修改代码)
如果不想调整参数,可先执行addDoc,再调用你已有的actualizarCrucero方法补充idCrucero字段:
async guardarCrucero( idCrucero: any, name: any, subtitle: any, imagenCrucero: any, descripcion: any, imagenDescripcion: any, tituloQueHacer: any[], imagenQueHacer: any[], descripcionQueHacer: any[], tituloCamarotes: any[], descripcionCamarotes: any[], imagenCamarotes: any[], planos: any[], lugares: any[], precioLugares: any[], puertos: any[] ) { const obj ={ // 暂时不包含idCrucero字段 "name" : name, "subtitle" : subtitle, "imagenCrucero" : imagenCrucero, "descripcion" : descripcion, "imagenDescripcion" : imagenDescripcion, "tituloQueHacer" : tituloQueHacer, "imagenQueHacer" : imagenQueHacer, "descripcionQueHacer" : descripcionQueHacer, "tituloCamarotes" : tituloCamarotes, "descripcionCamarotes" : descripcionCamarotes, "imagenCamarotes" : imagenCamarotes, "planos" : planos, "lugares": lugares, "precioLugares": precioLugares, "puertos": puertos }; const Ref = collection(this.firestore, 'Cruceros'); const docRef = await addDoc(Ref, obj); this.idCrucero = docRef.id; // 调用更新方法补充idCrucero字段 await this.actualizarCrucero(docRef.id, { idCrucero: docRef.id }); console.log(this.idCrucero); }
注意事项
- 方案一需要调整调用
guardarCrucero的地方,移除原idCrucero参数的传递; - 两种方案最终都能实现
idCrucero字段与Firestore文档ID一致的效果,优先选择方案一减少Firestore操作次数。
内容的提问来源于stack exchange,提问作者José Manuel Ruíz Bolaños
相关产品推荐
相关产品推荐

