I am trying to read data from firebase that is saved by childByAutoId(). I can successfully read the top half, but the reads what the childByAutoId() is. for example.
and in my firebase functions is
the logger -- uid is BoSwank... is correct, however on the line below for
logger -- workerId is -MBauxL.... is incorrect. That is the value of the childByAutoID() and it should be hkKplzF...
How I am trying to read this data is below.
exports.observeNotifications = functions.database.ref('/notifications/{cardUID}/{workerId}').onCreate((snapshot, context) => {
var uid = context.params.cardUID;
var workerId = context.params.workerId;
console.log('LOGGER --- uid is ' + uid);
console.log('LOGGER --- workerId is ' + workerId)
})
I thought changing
/notifications/{cardUID}/{workerId} to /notifications/{cardUID}/{cardUID/workerId}
and then changing
var workerId = context.params.workerId;
to
var workerId = context.params.cardUID.workerId;
would do the trick but it does not.
With Cloud Functions database triggers, the wildcards in the path only match the names of nodes. They never match the values of any children. What you are seeing right now is the expected behavior, and there's no way to change it.
If you want the value of children under the location that was matched in the path, you're going to have to reach into it using the snapshot parameter that was passed to the function. It is a DataSnapshot object, and contains all of the values of all of the children under the location that was matched in the path.
In your case, the value of workerId is going to be found like this:
const workerId = snapshot.val().workerId
I suggest reading over the documentation for more complete information about how database triggers work.
Related
Let me preface this by saying I'm sure it's something amazingly simple and stupid that I'm missing but I've been trying to solve this for over a week now and it's breaking my brain. I'm building a web app to do quoting for my workplace and most of it is working fine. I'm at a point where I need to take an object composed of a bunch of data from dynamically created user inputs and access it from the node server so that I can put that data into my mongodb database.
Through trolling through answers to similar questions I've been able to figure out that putting data into a hidden input I've named "quoteoutput" and then retrieving that using req.body.quoteoutput seems to be the way to go. As the submit function runs I do a console.log to check the variable actually has the stringified json object stored as a string, this shows up exactly as expected.
However when I get to the Node side of things the variable shows up as empty.
Hidden Input Declared in HTML:
<input type"hidden" name="quoteoutput" value="" />
Javascript to Change the Value to the stringified object:
outvalue = {customername: customer, quotelines: lines};
var output = document.getElementsByName("quoteoutput");
output.value = JSON.stringify(outvalue);
console.log("Output Value is:" + output.value);
The console in Chrome then displays exactly what is expected on the console.log
Post Request:
router.post('/addquote', function(req, res) {
var receivedobj = req.body.quoteoutput;
console.log("Object is " + receivedobj);
res.send("OBJ Is " + receivedobj)
};
The next step would be to parse the string back into a JSON object so I can start compiling it to be put into the MongoDB Database appropriately but receivedobj is just showing up as blank, there is no string to parse back in. So that the output I get in the console.log here is:
"Object Is "
And the res.send call brings up a blank page with:
"OBJ is"
And nothing else, apologies if this is a duplicate, I really tried searching for it somewhere else but couldn't find it.
By default, Express does not read the body of the post. You need some code that actually reads the body from the stream and then parses it based on its content-type. You don't show the whole client-side code to know exactly what content-type it is sending. If it's a form, then it would be probably be application/x-www-form-urlencoded which you can read and parse with express.urlencoded() like this:
router.post('/addquote', express.urlencoded(), function(req, res) {
var receivedobj = req.body.quoteoutput;
console.log("Object is " + receivedobj);
res.send("OBJ Is " + receivedobj)
});
Or you can generically install that middleware so it will work for all POST or PUT requests with that content-type:
router.use(express.urlencoded());
router.post('/addquote', function(req, res) {
var receivedobj = req.body.quoteoutput;
console.log("Object is " + receivedobj);
res.send("OBJ Is " + receivedobj)
});
Or, at the app level, you can do:
app.use(express.urlencoded());
Installing it as middleware will examine the incoming request. If it's the type of request that has a body to it (like POST or PUT) and it has a matching content-type, then the middleware will read the rest of the incoming stream to get the body contents and then parse it according to its content type and then place the results into req.body for your actual request handler, further down the line to access.
It also looks like your client code might be a bit off because document.getElementsByName() returns a collection and you have to index that collection to access one particular object:
outvalue = {customername: customer, quotelines: lines};
var output = document.getElementsByName("quoteoutput")[0]; // see the [0] here
output.value = JSON.stringify(outvalue);
console.log("Output Value is:" + output.value);
This will set the actual .value property on the first DOM element with the "quoteoutput" name attribute.
I have created a realtime database on firebase and having no issues adding and removing data in tables etc.
I currently have it setup like this:
So my goal is to check if a given value is inside my database currently.
for example, I would like to check if 'max' is currently a username in my database.
var data = db.ref('loginInfo/');
data.on('value', function(snapshot) {
_this.users = snapshot.val()
});
That is how I get all the values, it is saved into _this.users
(How do i check if a value is inside this object, i am making a login program)
if i console.log the object, this is what I see:
image
If you want to check if a child node exists under loginInfo where the username property has a value of max, you can use the following query for that:
var ref = db.ref('loginInfo/');
var query = ref.orderByChild('username').equalTo('max');
query.once('value', function(snapshot) {
console.log(snapshot.exists());
});
I'd also recommend reading the Firebase documentation on queries, as there are many more options.
I'm currently in the proccess of making a web application for a university project and I need some help in retrieving a value in the Firebase database. Here is the structure:
What im trying to do is see if a specific uid is present anywhere unfer the ref 'addresses'
this is my code:
var refAdd = firebase.database().ref().child('addresses');
refAdd.orderByChild("uid").equalTo(user.uid).once("value", function(snapshot){
console.log("(snapshot) request found for " + snapshot.key);
snapshot.forEach(function(child) {
console.log("request found for " + child.key);
});
});
So what I'm trying to do here is see if ther current user UID is present under 'addresses', if it is then log the push key value where it's located.
Anyone one have any idea on how to go about it?
The best approach would probably be to denormalize your data. That means that each time you write a "request" for a specific user under a specific "addresses" item you should also write, in another database node the "push" id of the "address" under the uid of the user.
In other words, based on your example you should have a database like:
- addresses
+ -LAPf7dNDU...
+ requests
- ......
- addressesByUid
- 9nras7IY..... //You use the user uid as the key of this node
- adressId: "-LAPf7dNDU..." //The key of the address
In such a way your query will be much easier.
The only "difficulty"is the fact that you have to maintain the two nodes in sync. But this can be easily done with e.g. an set of writes like in the following example (from the doc):
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
Finally, note that, if necessary, you could have several addressIDs under a user uid by doing something like
- addressesByUid
+ 9nras7IY..... //You use the user uid as the key of this node
- -LAPf7dNDU...: "true"
- -LUTTE66hf...: "true"
Problem
In a social media app I am making with react native and firebase, I am trying to grab the number of comments a post has using the snapshot function of a variable I have saved on my servers, then I am going to add one to this variable when a user adds a new comment. My code to do so is right here:
firebase.database().ref('posts').child(this.state.passKey).update({
comments: firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
})
When I actually run this code, I get an error saying:
Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".","#","$","[", or "["
At first I thought this might be that the "this.state.passKey" wasn't actually passing the key, but putting in a key I copied from the server didn't fix the problem.
My Server
-
To get the comments of particular post you should do like this
let postId='someId'
postRef=`/posts/${postId}`
firebase.database().ref(postRef).once("value", dataSnapshot => {
comment=dataSnapshot.val().comments
});
It looks like you're expecting this bit of code to query the database:
firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
Unfortunately, it doesn't work that way. There's no snapshot property on a database Reference object returned by child() or ref().
Instead, you'll need to query the database at that reference, then when you're called back with its value, you can apply it elsewhere.
var ref = firebase.database().ref('posts/'+this.state.passKey+'/comments')
ref.once('value', function(snapshot) {
// use the snapshot here
})
I am making an express app with Parse. In my cloud code, I am trying to get an attribute of the current user, but it is returning me undefined. My code looks like following:
app.get('/home/subscriptions',function(req,res){
Parse.Cloud.useMasterKey();
var user = Parse.User.current();
var ifstud = user.get("isStudent");
console.log('student: ' + ifstud); // undefined
console.log('id: ' + user.id); // OK. works fine.
}
I am able to retrieve the id of the user as above but not able to call the get method on user. In their API reference, they have mentioned that Parse.User.current() returns a Parse.Object, so I think in user I have _User object and I should be able to call all methods supported by a Parse.Object.
What might be the issue here?
Thanks
I figured it out and putting this answer for future reference to users who visit this question.
The Parse.User.current() returns only a pointer to the user and not the complete user object. To get access to all fields of the user, fetch the entire object using the fetch method.
var fullUser;
Parse.User.current.fetch().then(user){
fullUser = user;
}).then(function(){
// Place your code here
});
I think it should be: var ifstud = Parse.User.get("isStudent");