Remove a value from Firebase Array - angularjs

I have a array in firebase created using the push() function.
I am trying to remove a specific value in that array.
var arr = $firebaseArray(ref.child('invoices').child('pending').child(coId));
arr.$loaded().then(function(){
var index = arr.$getRecord(invoiceId);
arr.$remove(index);
})
However, this is not working. I keep getting -1 for the var index. If there is an easier way to remove a value, with or without angularFire, I would be open to it.
Thanks!

I made a plunker for your case and it works:
var ref = new Firebase('https://benjaminsuch.firebaseio-demo.com/'),
arr = $firebaseArray(ref.child('invoices'));
arr.$loaded().then(function() {
var index = arr.$getRecord('item123423');
console.log('index', index);
arr
.$remove(index)
.then(function() {
console.log('item removed')
})
.catch(function(error) {
console.log('error', error);
});
});
Maybe you provide us a plunker too with your code, so we can see whats going on.

Related

React Promise Return Firebase Array

I am having a really hard time solving this issue I'm currently having. You see, I am using Firebase as my database to store and fetch data.
Right now, I want to be able to return an array that is being made inside a Firebase .once call, but I am having some difficulties. This is my code so far:
Calling the function (a return function):
<p>{this.fetchStartingPrice(singleProduct.id)}</p>
This is where I want to display the specific value, that I am trying to fetch down below:
fetchStartingPrice(category){
let promises = [];
promises.push(this.fetchPrices(category));
Promise.all(promises).then(result => {
console.log(result);
})
}
I have just used a console.log in an attempt to troubleshoot errors.
fetchPrices(category){
var allPrices = [];
allProductsFirebase.child(category).once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
if(childSnapshot.key == category){
allPrices.append(childSnapshot.val().brand);
}
});
return allPrices;
})
}
So basically, I want to loop through the allProductsFirebase in an attempt to first identify the brand of the product, and if it matches with the brand that has been used as a parameter in fetchStartingPrice() and fetchPrises(), I want to store the specific price of that product in an array of numbers (prices). After I have looped through the whole snapshot, I want to return the full array containing only product prices, and then through fetchStartingPrice(), I want to use Math.min(promises) to grab the lowest number in that array. However, I am having a really hard time doing this. Could someone please help me with this?
I want to be able to then, after all of this, return the value in fetchStartingPrice().
fetchPrices() must return Promise or be Promise. you are returning nothing from fetchPrices() ( you are returning allPrices in the .once() scope ). try to return the result ( if it returns Promise ) that .once() returns.
fetchPrices(category){
var allPrices = [];
return allProductsFirebase.child(category).once('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
if(childSnapshot.key == category){
allPrices.append(childSnapshot.val().brand);
}
});
return allPrices;
})
}

iterate each object in array and populate each element of the array with result. asynchronously

I need help with array asynchronous iterate functionality. I working with node-opcua library in nodejs. There is function session.browse(nodeId, result)
Right now code looks like:
NodesTree = {
"NodesTree":{
"name":"SYM:",
"subf":[]
}
};
the_session.browse("ns=1;s=SYM:", function(err, browse_result){
if(!err) {
var buf = [];
browse_result[0].references.forEach(function(reference) {
if (reference1.browseName.namespaceIndex > 1) {
buf.push(reference);
}
});
NodesTree.subf = buf;
}
});
In result I get references of SYM: folder example:
[{"referenceTypeId":"ns=0;i=35","isForward":true,"nodeId":"ns=6;s=S71500ET200MP station_1","browseName":{"namespaceIndex":6,"name":"S71500ET200MP station_1"},"displayName":{"text":"S71500ET200MP station_1","locale":"en"},"nodeClass":"Object","typeDefinition":"ns=0;i=61"}]
I have Nodes structure in opc like this:
->SYM:
-->PLC
--->PLC_name
---->global_tag <variable>
---->global_tag1 <variable>
---->block
------>blok_tag1 <variable>
------>block_tag2 <variable>
Task is make one complete JSON object as tree for further use.
Logic is that: for each element in the references array get nodeId value and browse for references of the element and assign as element.subf = reference.
Final result something like:
NodesTree = {
"NodesTree":{
"name":"SYM:",
"subf":[
{attributes of PCL structure got by **browse**() + subf:[{ attributes of PLC_name by browse(), subf:
[{....and here again attributes and subf] }, {if no subf just assign subf; [] }]
]
}
};
So need call session.browse() for each reference and all finally bind to one object.
I tried to use Async library each and map in series functions to solve all that, but get nothing wise in result. May be there some smart solution can be found by Stack overflow community. Please help.
I am not familiar with node-opcua but assume that session.browse() is also async. Then something like this might work?
var async = require('async');
async.map(buf,
function(reference, callback) {
session.browse(reference.nodeId, function (err, result) {
callback(err, result);
});
}, function(err, results) {
// results is now an array of all single results
NodesTree.subf = results;
});

Mongoose Init Arrays with empty array instead of undefined

After some debugging, I came up with this code:
var trackSchema = new mongoose.Schema({
title: String,
playedAtTimestamps: Array
});
trackSchema.post('init', function(track) {
track.playedAtTimestamps = track.playedAtTimestamps || [];
});
So that anywhere else in the code, I know track.playedAtTimestamps is an Array. But I have the feeling my post-init callback is redundant to my Schema definition.
Is there a better practice? Should we somehow modify Mongoose's behavior?
Thanks
Gotcha :facepalm
I was doing
Track.findOne({})
.select('title') // Here is the mistake, I was not fetching playedAtTimestamps
.exec(function(err, track){
console.log(track);
track.incCounterSync((new Date()).getTime()); // Here is the error
track.save(function(err, track){
console.log(track);
});
});

protractor return array of values from repeater

I am looking for an easy way to return an array of values from protractor's all.(by.repeater)
Basically, I just want an easy way to make an array of usernames given a repeater like user in users.
Right now I'm building it like this:
allUsers = element.all(by.repeater('user in users').column('user.username')).then(function(array){
var results = []
var elemLength = array.length
for(var n = 0; n < elemLength; n++){
array[n].getText().then(function(username){
results.push(username)
})
}
return results
});
expect(allUsers).toContain(newUser)
Is there a more concise, reusable way to do this built into protractor/jasmine that I just can't find?
AS alecxe said, use map to do this. This will return a deferred that will resolve with the values in an array, so if you have this:
var mappedVals = element.all(by.repeater('user in users').column('user.username')).map(function (elm) {
return elm.getText();
});
It will resolve like this:
mappedVals.then(function (textArr) {
// textArr will be an actual JS array of the text from each node in your repeater
});
I've successfully used map() for this before:
element.all(by.repeater('user in users').column('user.username')).map(function (elm) {
return elm.getText();
});
When I researched the topic I took the solution from:
protractor - how to get the result of an array of promises into another array

Returning values of a fetch

Please look at the code below. It's a Backbone/Parse code that uses some underscore features.
I'm trying to iterate over an Parse class to retrieve "firstName" attributes of all objects in that class.
I have 2 issues with it.
The first one, as indicated with the comment, is that it correctly retrieves the first names, but it duplicates them. So if there are 5 objects, it will retrieve 5 firstName * 5. There is an iteration problem here. This is shown with the console log.
Second problem, is that I try to push firstName values into an array, then return it, so I can use the values later in code using the testt variable. But checking the testt content with a console log sends a message instead of the firstname lists.
Do you see anyway how to fix this code ?
var DoopizCollection = Parse.Collection.extend({
model: Subscribers
}
);
var doopizlist = new DoopizCollection();
var testt;
testt = doopizlist.fetch({
success: function(doopizlist) {
var results = [];
doopizlist.each(function(object) {
results.push(doopizlist.pluck('firstName'));
console.log(doopizlist.pluck('firstName')); // logs 2 duplicate arrays
});
return results;
},
error: function(doopizlist, error) {
console.log("error"); // The collection could not be retrieved.
}
});
console.log(testt); // logs "a b.promise...." message instead of firstNames
The duplication issue is because you are looping over doopizlist twice, once with each and again with pluck. Pluck is just basically shorthand of the map method.
The second issue is, you are expecting testt is the resulting value, when actually it is an instance of jqXHR, which is something known as a promise. So you can use the then method to log the value of the result.
var DoopizCollection = Parse.Collection.extend({
model: Subscribers
}
);
var doopizlist = new DoopizCollection();
var testt;
testt = doopizlist.fetch({
success: function(results) {
return results.pluck('firstName');
},
error: function(results, error) {
console.log("error"); // The collection could not be retrieved.
}
});
testt.then(function(results) {
console.log(results);
});

Resources