javascript - 如何使用现有数据以及随机生成的 ID 更新我的 firebase 实时数据库中的数据

标签 javascript node.js firebase firebase-realtime-database google-cloud-functions

我正在将数据从表单发送到我的数据库。正如我所理解的那样,使用 .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
  });
})

这是我的实时数据库中数据结构的图像。 database structure

最佳答案

我认为您打算在函数中使用通配符以捕获该 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/

相关文章:

Javascript 不读取以 0 开头的数组项

Javascript 检查未定义问题

node.js - 如何限制CSS仅在特定npm包中受影响?

ios - Firebase 与 FB SDK 登录冲突

firebase - 为小部件调用两个不同端点的最佳实践?

javascript - 在 asp.net 中运行代码时,React 组件未显示

Javascript/Node/Express : res. json需要等待一个函数运行完毕才返回...但是res.json不耐烦?

javascript - 可能的 Controller 或至少执行两次的函数

javascript - 如何正确回收 JavaScript 中的缓冲区

node.js - 将自定义信息添加到 Firebase 函数中的 Stackdriver 错误日志