Firebase batch()函数没有更新多个文档



我正在尝试使用批处理更新firebase中的多个文档。该功能正在运行,没有任何错误,但没有更新所需的字段


let newDbRef = db.collection( 'oldusers' ).where( 'userName', '==', newUserName.value )
newDbRef.onSnapshot( ( querySnapshot ) =>
{
querySnapshot.forEach( ( doc ) =>
{
var batch = db.batch()
batch.update(newDbRef, {'userName': newUserName.value})
batch.commit().then( () =>
{
console.log('profiles updated...');
})
})
})

我该如何解决这个问题?

您不应该在forEach循环中声明和提交批处理。当您添加了所有更新操作时,在循环之前声明它,并在循环之后提交它,如下所示:

let newDbRef = db
.collection('oldusers')
.where('userName', '==', newUserName.value);
newDbRef.onSnapshot((querySnapshot) => {
var batch = db.batch();

querySnapshot.forEach((doc) => {
batch.update(newDbRef, { userName: newUserName.value });
});

batch.commit().then(() => {
console.log('profiles updated...');
});
});

请注意,由于使用onSnapshot(),每次查询结果发生更改时(即添加、删除或修改文档时(,都会发生批量更新

最新更新