[英]How do I write data to firestore when creating a new user?
I'm trying to create a data entry on the firebase database to store additional information about a user when they register on my site.我正在尝试在 firebase 数据库上创建一个数据条目,以在用户在我的网站上注册时存储有关用户的其他信息。
I've tried to write data to the database in the.then() function following createUserWithEmailAndPassword() as that's the only way for me to extract the user id for the user (I'm hoping to use the uid as the key field of the record I create)我尝试在 createUserWithEmailAndPassword() 之后的 the.then() function 中将数据写入数据库,因为这是我为用户提取用户 ID 的唯一方法(我希望使用 uid 作为我创建的记录)
(req, res) => {
// extract user data from the form
const newUser = {
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
pw: req.body.pw,
pw_c: req.body.pw_c
}
// carry out validation
const { valid, errors } = validateRegistrationData(newUser);
if (!valid) return res.status(400).json(errors);
// create new firebase user
firebase
.auth()
.createUserWithEmailAndPassword(newUser.email, newUser.pw)
.then(data => {
let uid = data.user.uid;
// make a database entry to store the users info
// by default, assumes that the user is a secondary user
let userData = {
fname: newUser.fname,
lname: newUser.lname,
email: newUser.email,
utype: 1,
createdon: admin.firestore.FieldValue.serverTimestamp(),
intitems: []
}
newUserDoc = db
.collection("users")
.doc(uid)
.set(userData)
return res.status(200).json("Success: new user created.");
})
.catch(err => {
if (err.code === "auth/email-already-in-use"){
return res.status(400).json({ email: "Email is already in use" });
} else {
return res.status(500).json({ error: err.code });
}
});
return res.status(200).json("Success: new user created.");
}
The server responds with {Success: new user created."}
. The authentication part seems to work as a new user is created in the Authentication
section of my firebase console. However, no new data entries appear in the users
collection of my database.服务器以{Success: new user created."}
响应。身份验证部分似乎可以工作,因为在我的 firebase 控制台的Authentication
部分中创建了一个新用户。但是,我的数据库的users
集合中没有出现新的数据条目。
.set
returns a promise that still needs to run to completion. .set
返回一个仍需要运行完成的 promise。 However, currently you're not waiting on the promise, and instead just responding via res.send
.但是,目前您不是在等待 promise,而是通过res.send
响应。
You can append.then(() => { do stuff here }) to the end of .set
.您可以 append.then(() => { do stuff here }) 到.set
的末尾。 If it's the last thing you're doing in that function, you can just do res.send from there.如果这是你在 function 中做的最后一件事,你可以从那里做 res.send。
return db.collection("users").doc(uid).set(userData).then(() => {
return res.status(200).json("Success: new user created.");
})
.catch(error => {
console.log(error)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.