我正在将数据从表单发送到我的数据库。正如我所理解的那样,使用 .push() 创建了一个唯一的 ID,我的数据被附加到并上传到其中。我现在需要获取相同的数据,然后添加一个新的 ID 条目。但我无法引用数据,因为它存储在由 .push() 方法创建的唯一 ID 下。
exports.addUser = functions.https.onRequest(async (req, res) => { //Adds data from the form to the database
cors(req, res, async () => {
// Grab the message body parameter.
const entry = req.body;
// Push the new message into the Realtime Database using the Firebase Admin SDK.
const snapshot = await admin.database().ref('entries/users/').push(entry);
console.log('my new shiny id is ' + snapshot.key());
// Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
res.redirect(303, snapshot.ref.toString());
})
});
//Function to generate a random ID and update into the entry from the form on the database.
exports.generateID = functions.database.ref('entries/users/').onCreate((snapshot, context) => {
console.log(snapshot.val());
const original = snapshot.val();
console.log(context);
console.log(snapshot.key());
const dev = '0eeb94ca-3426-46ca-964d-a9bdd7d00ef0';
var random = Math.random().toString(36).substring(7);
const code = uuidv5('user-' + random, dev);
return snapshot.ref.update({
userID: code
});
})
最佳答案
我认为您打算在函数中使用通配符以捕获该 ID(并且还仅在该新 Node 上触发):
functions.database.ref('entries/users/{id}').onCreate((snapshot, context) => {
现在您可以使用 context.params.id
获取该 ID,并在该新 Node 下更轻松地写入。
关于javascript - 如何使用现有数据以及随机生成的 ID 更新我的 firebase 实时数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58616671/