TL;DR:OP 正在更新具有相同值的记录,因此 Firestore 数据库中似乎没有任何变化。但是,在他的代码中,需要返回单个异步操作(或一组异步操作)返回的承诺
由于您可能要对数据库并行执行多个异步操作(使用返回承诺的update() 方法,请参阅doc),您需要使用 Promise.all(),如下。
saveEditUser() {
const email = this.form.email;
const= promises = [];
db.collection('users')
.where('email', '==', email )
.get()
.then(snap => {
snap.forEach(doc => {
promises.push(
doc.ref.update({
email: email //Actually the problems comes from here, see below
})
);
return Promise.all(promises);
})
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}
如果您 100% 确定您的查询将只返回一个文档,您可以直接更新该文档,但是您必须返回 update() 返回的承诺,如下所示:
saveEditUser() {
const email = this.form.email;
db.collection('users')
.where('email', '==', email)
.get()
.then(snap => {
return snap.docs[0].ref.update({
email: email
});
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}
注意:通过在函数开头声明email const,您应该不会再遇到任何上下文问题。
在我们的 cmets 和讨论之后更新:
实际上,您正在使用 email 的相同值进行更新。所以看不到任何结果是正常的。只需尝试使用另一个值进行更新,例如以下代码:
saveEditUser() {
const email = this.form.email;
db.collection('users')
.where('email', '==', email)
.get()
.then(snap => {
return snap.docs[0].ref.update({
email: 'john.doe@gmail.com'
});
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}
如果您想使用表单中的值进行测试,只需使用两个字段:一个带有要查询的值,一个带有新值,例如:
<input v-model="form.mail" placeholder="mail to search for">
<input v-model="form.newMail" placeholder="new email">
.....
saveEditUser() {
const emailToQuery = this.form.email;
const newEmail = this.form.newMail;
db.collection('users')
.where('email', '==', emailToQuery )
.get()
.then(snap => {
return snap.docs[0].ref.update({
email: newEmail
});
})
.then(() => {
console.log('Successfully updated the record')
})
.catch(error => {
console.error('There was an error editing the record: ' + error)
})
}