Javascript 如何使用批处理创建多个文档?
我有这段代码,我试图用bacth在我的集合中创建新字段,我想用这个条件((索引+1)%500==0)来验证是否使用提交,有什么问题吗Javascript 如何使用批处理创建多个文档?,javascript,firebase,google-cloud-firestore,Javascript,Firebase,Google Cloud Firestore,我有这段代码,我试图用bacth在我的集合中创建新字段,我想用这个条件((索引+1)%500==0)来验证是否使用提交,有什么问题吗 const myFunction = async () => { try { let batch = db.batch() const batchCommits = [] await schoolList.forEach(async (school, index) => { await ref
const myFunction = async () => {
try {
let batch = db.batch()
const batchCommits = []
await schoolList.forEach(async (school, index) => {
await ref
.doc(school.id)
.collection('mycollection')
.where('visual', '==', 'none')
.get()
.then(async (querySnapshot) => {
if (querySnapshot.empty) {
const curses = await ref
.doc(school.id)
.collection('curses')
.doc()
batch.set(curses, common)
if ((index + 1) % 500 === 0) {
batchCommits.push(batch.commit())
batch = db.batch()
}
}
})
})
batchCommits.push(batch.commit())
return Promise.all(batchCommits)
}
}
我收到以下错误:错误:无法修改已提交的写回。我的理解是,您可以使用for-of循环(即for(const-school-of-Schools))处理结果。这是相当粗糙的,但可能像下面这样?不太确定是否将批次组合成承诺 如果你已经解决了这个问题,请发布你的解决方案
let batch = db.batch()
for( const school of schoolList) {
const myCollectionDoc = await ref.collection('mycollection')
.doc(school.id)
.get()
if(myCollectionDoc.empty) {
const curses = await ref.doc(school.id).collection('curses').doc()
batch.set(curses, common)
}
if (batch._writes.length === 500) {
await batch.commit()
batch = db.batch()
}
}
if (batch._writes.length != 0) {
await batch.commit()
}
await
在forEach循环中的工作方式与预期不同。它不会阻止每次迭代,forEach也不会返回另一个等待的承诺。尝试:wait Promise.all(schoolList.map(…)
@DougStevenson我删除了wait,但错误仍在继续