在 Firestore 的循环中使用带有批处理方法的更新

Using update with batch method in a loop in Firestore

在 Firestore 中,我尝试使用批处理方法循环更新文档。

这段代码如何工作:

var batch = this.afs.firestore.batch();
var eventRef = this.eventCollection.doc(eventkey).ref;
batch.update(eventRef, updateField );
var artistRef = this.memberCollection.doc('7yLf6RgLIIEUkAJ3jbXy').collection('events').doc(eventkey).ref; 
batch.update(artistRef, updateField); 
var artistRef = this.memberCollection.doc('eJtcLZrUZhhObWcmptQs').collection('events').doc(eventkey).ref; 
batch.update(artistRef, updateField); 
batch.commit().then(function() {console.log('success')};

但是这个不行:

var batch = this.afs.firestore.batch();
var eventRef = this.eventCollection.doc(eventkey).ref;
batch.update(eventRef, updateField );
if(artists) {
  Object.values(artists).forEach(function(artist) {
    var artistkey = artist.$key;
    var artistRef = this.memberCollection.doc(artistkey).collection('events').doc(eventkey).ref;
    batch.update(artistRef, updateField); 
  });
}
batch.commit().then(function() {console.log('success')};

它告诉我"ERROR TypeError: Cannot read property 'memberCollection' of undefined"

由于您在回调函数内部,this 的含义与外部不同。

最简单的解决方案是将您的 memberCollection 分配给回调之外的单独变量:

var batch = this.afs.firestore.batch();
var eventRef = this.eventCollection.doc(eventkey).ref;
var memberCollection = this.memberCollection;
batch.update(eventRef, updateField );
if(artists) {
  Object.values(artists).forEach(function(artist) {
    var artistkey = artist.$key;
    var artistRef = memberCollection.doc(artistkey).collection('events').doc(eventkey).ref;
    batch.update(artistRef, updateField); 
  });
}
batch.commit().then(function() {console.log('success')};

但是您也可以对函数使用箭头语法,这样可以防止重新分配 this:

var batch = this.afs.firestore.batch();
var eventRef = this.eventCollection.doc(eventkey).ref;
batch.update(eventRef, updateField );
if(artists) {
  Object.values(artists).forEach((artist) => {
    var artistkey = artist.$key;
    var artistRef = this.memberCollection.doc(artistkey).collection('events').doc(eventkey).ref;
    batch.update(artistRef, updateField); 
  });
}
batch.commit().then(function() {console.log('success')};

这是一个非常常见的 JavaScript 问题,适用于任何有回调的地方(不仅仅是 Firestore)。我建议您查看之前关于此主题的一些问题:

  • How to access the correct `this` inside a callback?
  • Maintaining the reference to "this" in Javascript when using callbacks and closures