背景
我正在尝试使用网络应用中的初始用户列表为我的 Firebase 播种。这应该是一个两步过程:
- 使用
createUserWithEmailAndPassword()
将用户添加到 Firebase Auth方法。 - 使用
collection.add()
方法将用户添加到 Firestore 集合。
代码
// Initialize Firebase:
var db = firebase.initializeApp(config).firestore();
// Function to add a new user:
function add(email) {
firebase.auth().createUserWithEmailAndPassword(email, 'password')
.then(function (user) {
console.log('User created:', email, user.user.uid);
return db.collection('users').add({
email: email,
uid: user.user.uid
});
})
.then(function () {
console.log('Document created:', email);
})
.catch(function (error) {
console.error('Could not create user/document:', error);
});
}
// Seed database with random users:
for (var i = 0; i < 10; ++i) {
add(i + '@foo.bar');
}
问题
上一节中的代码不起作用。我的期望是它应该创建 10 个用户,并在成功时将 10 个相应文档添加到数据库中。但是,它仅将部分文档 (1-3) 添加到数据库,即使用户已正确创建。
想法
我对这段代码不起作用的可能原因提出了一些想法:
createUserWithEmailAndPassword()
方法不仅会创建新用户,还会执行自动登录。也许,这可能会导致某种竞争条件。createUserWithEmailAndPassword()
方法返回一个包含新注册用户的UserCredential
对象的 promise (我相信)。但是,我可能是错的,这个对象代表一个登录用户,这可能是上一点竞争条件的原因。- 我有可能以错误的方式使用 Promise,因为第二个
then()
和catch()
都没有被调用。
最佳答案
以下是 Firebase 支持答案的摘录:
Each time a new user is created with Auth, it sets the newly created user as the current user of the application. Whenever Firestore detects that a user change has occurred, it closes all outstanding streams and cancels any requests in flight.
这完全有道理并解释了这种行为。
关于javascript - 批量用户创建后 Firebase 不添加文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60848160/