Reputation: 127
I'm sending data from a form to my database. As I've understood correctly, using .push() creates a unique ID where my data is appended to and uploaded. I need to now get that same data and then add a new ID entry. But I can't reference the data since its stored under the unique ID created by the .push() method.
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
});
})
Here is an image of the data structure in my real-time database.
Upvotes: 1
Views: 93
Reputation: 127
All I needed to do was pass in a parameter into my ref url.
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/{id}').onCreate((snapshot, context) => {
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
});
})
The {id}
will stand as a parameter for the ID created by the .push()
method. The function will update the data entry with the generated ID.
Upvotes: 0
Reputation: 317467
I think you meant to use a wildcard in your function in order to capture that ID (and also trigger on only that new node):
functions.database.ref('entries/users/{id}').onCreate((snapshot, context) => {
Now you can use context.params.id
to get that ID, and write more easily under that new node.
Upvotes: 3