Reputation: 16141
I am learning Cloud Functions for Firebase. What I want is pass the key and value in the URL parameters, like:
https://xxx.cloudfunctions.net/addMessageSet?text=goodboy&key=testKey
And then in the Realtime Database set a testKey:goodboy
.
I know use push()
will generate a unique key (if i understood correctly) but I'd like use my own key each time. I am not sure if set()
works.
My problem is push({originalKey:original})
doesn't work as expected. It writes:
originalKey: goodboy
Where originalKey
is just key not the parameter from the URL. Is this possible or any other solutions?
The code is like below:
exports.addMessageSet = functions.https.onRequest((req, res) => {
// Grab the text parameter.
const original = req.query.text;
const originalKey = req.query.key;
admin.database().ref('/messages/').push({originalKey:original}).then(snapshot => {
console.log('goodboy', original, originalKey);
res.redirect(303, snapshot.ref);
});
});
Upvotes: 0
Views: 271
Reputation: 6421
If you want to use a key you're generating without firebase generating another you need to use set with your key in the path
admin.database().ref('/messages/' + originalKey).set(original).then(snapshot => { });
// if originalKey is not a string use String(originalKey)
You said about originalKey
not beeing a url, but everything in firebase if url based, like this you're doing
myDB
|_ messages
|_ originalKey: original
and not
myDB > messages > originalKey > original
If you need another key after the messages
node i recomend using a date UNIX number, momentJS is good to handle this.
Hope it helps
Upvotes: 1
Reputation: 973
Using push() will indeed generate a unique key. You will need to use either set() or update().
Note that using set() will overwrite the data at the specified location including any child nodes.
Upvotes: 0