Firebase query DataSnapshot val() returning null - javascript

My Firebase structure is below
{
"Test1 Lab" : {
"Equipment" : "3-D printer",
"Hours" : "7AM-6PM",
"Location" : "Library",
"Name" : "Digital Lab"
},
"Test2 Lab" : {
"Equipment" : "Oculus",
"Hours" : "7AM-6PM",
"Location" : "Hall",
"Name" : "Test Lab"
}
}
The top level is called "makerspace". I am trying to get the Name, Equipment, and Hours of the item where the Location is "Library" I ran the code:
var red = database.ref('makerspace');
return red.orderByChild('Location').equalTo("Library").once('value').then(function(snapshot){
console.log(snapshot.child("makerspace").child("Name").key);
});
And I get "Name". However, when I change .key to .val(), I should expect to get "Digital Lab", but I get null. I don't know how to fix this.

The snapshot is already on the makerspace node, so it should be:
var red = database.ref('makerspace');
return red.orderByChild('Location').equalTo("Library").once('value').then(function(snapshot){
console.log(snapshot.child("Name").val());
});

Try this
var red = database.ref('makerspace');
return red.orderByChild('Location').equalTo("Library").once('value').then(function(snapshot){
snapshot.forEach(function(data) {
console.log(data.val());
});
});

I would recommend to access snapshot data like this,
red.orderByChild('Location').equalTo("Library").once('value').then(function(snapshot){
console.log(snapshot.val()); <==========
// result would be
{ "Test1 Lab" : { "Equipment" : "3-D printer","Hours" : "7AM-6PM","Location" : "Library","Name" : "Digital Lab" } }
}
To get properties you can do,
snapshot.val()['Test1 Lab']['Name'] or snapshot.val()['Test1 Lab'].Name
snapshot.val()['Test1 Lab']['Hours']
Now you can get 'Test1 Lab' using Object.keys(snapshot.val())[0]
snapshot.val() is like JSON Object, so just access its properties like you did for objects. No need to use child() method to access data.

Related

MongoDB unset removes everything in child

I have a db structure like this:
{ "_id" : ObjectId("5fd48e12e5e0fd174c1a7260"),
"races" : {
"example1" : { "date" : "12/18/2020", "status" : "pending" },
"example2" : { "date" : "12/18/2020", "status" : "domestic" }
}
and I am attempting to just remove example 1 by using the following block of code(javascript):
self.db = client.db("authinfo");
self.collection = self.db.collection("users");
this.delete_both_races = function (user1) {
self.collection.updateOne({user:user1} ,{$unset:{races:"example1"}} ,function(error,result){});
same thing happens when running the following command in the mongo.exe command line program:
db.users.updateOne({user:"anything"} , {$unset:{races:"example1"}})
I get the result of(remaining elements after unsetting) :
{ "_id" : ObjectId("5fd48e12e5e0fd174c1a7260") }
desired result :
{ "_id" : ObjectId("5fd48e12e5e0fd174c1a7260"),
"races" : {
"example2" : { "date" : "12/18/2020", "status" : "domestic" }
}
You should unset races.example1 instead of races.
From MongoDB document,
The specified value in the $unset expression (i.e. "") does not impact the operation.
To specify a in an embedded document or in an array, use dot notation.
Mongo Playground

How to update a String with an Array in a document within Robo3T?

I am trying to change an element object that is within an array in a document on Robo3T.
The structure looks like this:
{
"_id" : ObjectId("1234"),
"source" : "BW",
"sourceTableName" : "lwtrmls",
"tableName" : "tier",
"type" : "main",
"primaryKeys" : [
{
"sourceField" : "tier_id", // <~~~~ This is what I am trying to update!
"reportingField" : "bw_id",
"type" : "integer"
}
]
}
Basically trying to change tier_id under primaryKeys and sourceField to trmls_id.
I have tried something like db.my_collection.update( {_id : "1234"}, {$set : {"primaryKeys.0.tier_id" : "trmls_id"}} ) and that does not seem to be working. Is there a clean way to do this?
Basically you need to use $(update)
In you case you need to execute current query:
db.my_collection.update( {_id : "1234", "primaryKeys.sourceField":"tier_id"}, {$set : {"primaryKeys.$.sourceField" : "trmls_id"}} )
Updated:
If you want to update not only first element in array for current filters, but all, you could use $[]
db.my_collection.update( {_id : "1234", "primaryKeys.sourceField":"tier_id"}, {$set : {"primaryKeys.$[].sourceField" : "trmls_id"}, { multi: true }} )

Angular / Meteor: Array is undefined

I'm building an Angular / Meteor application, using Meteor's reactivity to populated an Angular model. It is all working fine until I start working with arrays.
// get sentence
$scope.sentence = $meteor.object(Sentences, $stateParams.sentenceId);
// related sentences
$scope.relatedSentences = $meteor.collection(function() {
return Sentences.find({_id: { $in: $scope.sentence.relatedSentences }});
});
I get this error on the JavaScript console
Error: $in needs an array
at Error (native)
at Object.ELEMENT_OPERATORS.$in.compileElementSelector (http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:1894:15)
at http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:1576:19
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js? 0a80a8623e1b40b5df5a05582f288ddd586eaa18:164:22)
In the Mongo / Meteor console
meteor:PRIMARY> db.sentences.find({_id: "sp75iWPNqpbp2ypmy"});
{ "_id" : "sp75iWPNqpbp2ypmy", "sentence" : "Here is sentence 1 ", "language" : "en", "level" : "A1", "public" : true, "relatedSentences" : [ "wNs4ByDq7t396WLM3" ] }
And
meteor:PRIMARY> db.sentences.find({_id: { $in: [ "wNs4ByDq7t396WLM3" ] }});
{ "_id" : "wNs4ByDq7t396WLM3", "sentence" : "Here is sentence 0 ", "language" : "en", "level" : "A1", "public" : true, "relatedSentences" : [ ] }
I then commented out the failing find and have outputted the objects to html
$scope.sentence = $meteor.object(Sentences, $stateParams.sentenceId);
$scope.test = typeof $scope.sentence.relatedSentences;
Sentence: {{sentence}}<br/>
Related: {{sentence.relatedSentences}}<br/>
Typeof: {{test}}
Results
Sentence: {"autorunComputation": {"stopped":false,"invalidated":false,"firstRun":false,"_id":47,"_onInvalidateCallbacks": [null,null],"_parent":null,"_recomputing":false},"_id":"oFMp7swYyQsXkYsKz","sent ence":"Here is sentence 2","language":"en","level":"A1","public":true,"relatedSentences": ["wNs4ByDq7t396WLM3"]}
Related: ["wNs4ByDq7t396WLM3"]
Typeof: undefined
The Array is marked as undefined, but it is clearly shown in the full object. What am I missing?
EDIT
When running the above test on Firefox it returns an object
Related: ["wNs4ByDq7t396WLM3"]
Typeof: object
Related issue
$scope.test is only bound one time when this code initially runs. There is no data binding, so even if $scope.sentence.relatedSentences changes, test will not. The issue is that $scope.sentence.relatedSentences is populated asynchronously.
This would also apply to $scope.relatedSentences -- you are trying to set it initially before $scope.sentence.relatedSentences is available. You can use .subscribe on the value returned from .object to set this once the data is available.
$scope.sentence.subscribe().then(function () {
$scope.relatedSentences = $meteor.collection(function() {
return Sentences.find({_id: { $in: $scope.sentence.relatedSentences }});
});
});

formatting a json object

Im trying to use json to store some values from a page and then access these values/variables
later in a php file. Now the thing is that I'm new to json and javascript in general and Im
struggling for hours to find a solution to a problem that might be stupidly simple for you
guys who have experience in this:
Now I have this:
var invoice_data = {
"client":[
{
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
],
"shoppingcart":[
{
"1" : {"item-name":"", "qty":"", "price":"", "discount":"", "subtotal":""}
}
],
};
So is this inheritance thing im not really getting. So just as I've created "client" object
im creating "shoppingcart", now the thing is that when user orders more than an item there should be created another sub-object that would store it's details too.So im assuming like:
"shoppingcart":[
{
"1" : { "item-name":"", "price":"", "discount":"" }
"2" : { "item-name":"", "price":"", "discount":"" }
}
],
So when I console.log(invoice_data.shoppingcart); I get the "shoppingcart" object, but I
cant access invoice_data.shoppingcart.1 or invoice_data.shoppingcart.2, is there any way I can access 1 or 2 sub-object just as access invoice_data.shoppingcart or invoice_data.client?
Thank you.
Edit: I can access it as an array, im not interested in that option. Ideally i'd like to access the sub-object via it's name.
Remove the array syntax:
Change this:
"client":[
{
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
]
to this:
"client": {
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
The same goes for shopping cart.
You can't access invoice_data.shoppingcart.1 because 1 is not a valid Javascript variable name. If the key for an object isn't a valid variable name, you have to use array notation: invoice_data.shoppingcart[1].
EDIT: I didn't see it, but as Matt pointed out, you must remove the array syntax as well.
Your shopping_cart is an array.
You don't want:
shopping_cart : {
1 : { name : "...", price : "..." },
2 : { ... }
}
You want:
shopping_cart : [
{ name : "..." },
{ ... }
]
Then you would access that by saying:
shopping_cart[0].name;
shopping_cart[0].price;
Et cetera.
Arrays also start at 0 and not 1.
And this isn't inheritance: it's just a collection of things.

mapping deep json

How to mapping this json ?, i have been trying with multiple argument on each, but still can't get the data.
{
"data" : {
"after" : "t3_qp79c",
"before" : null,
"children" : [ {
"data" : { "url" : "http://imgur.com/c0COJ" },
"kind" : "t3"
} ],
"modhash" : ""
},
"kind" : "Listing"
}
My javascript code
$.getJSON(reddit_api_url,function(data) {
$.each(data.children['data'], function(i, reddit) {
// Uncomment line below to show tweet data in Fire Bug console
// Very helpful to find out what is available in the tweet objects
// console.log(reddit);
// Before we continue we check that we got data
console.log(i+' : '+ reddit );
// Build the html string for the current tweet
var tweet_html = reddit.url;
// Append html string to tweet_container div
$('#tweet_container').append(tweet_html);
});
}
Thanks
The data returned has its own data property, so you'd need...
data.data.children[0]['data']
...to get to that innermost data.
If you were iterating the children, then you'd pass that to $.each...
$.each(data.data.children, function(i, obj) {
console.log(obj.data.url);
});

Categories

Resources