Angular-firebase. Data is not inserted correctly - angularjs

I want my data to be inserted in firebase like so :
cities:{
Tokyo:{
name: "Tokyo, JP"
}
London:{
name: "London, UK"
}
and so on...
I inserted some data manually from the online GUI : cities
But unfortunately it gets inserted so : minsk
My code
the Firebase factory:
export default function CitiesFactory($firebaseArray, Firebase) {
'ngInject';
var ref = new Firebase("https://name.firebaseio.com/");
return $firebaseArray(ref.child('cities'));
}
Controller (add function):
$scope.addoras = function(city) {
CitiesFactory.$add({
city: {
name: city
}
}).then(function(CitiesFactory) {
var id = CitiesFactory.key();
console.log('Added Contact ' + id);
$scope.addorasmodel = '';
});
};
Can someone help me?

When you use $add() it will generate a unique push id as it says in the documentation.
If you want to avoid these unique id's you can use set() or update() (Documentation)
var ref = new Firebase("https://name.firebaseio.com/");
ref.set({
city: {
name: city
}
});
var ref = new Firebase("https://name.firebaseio.com/");
ref.update({
city: {
name: city
}
});

Related

How to update array in Firebase and is this the right way to create one?

I created a code to add infos in one array and after this, stores it in the Firebase Database. The result is a numeric id from array. Ex: 0..1..2..3.
I'm trying to update field atual with different value from a <input> and got an error. Here's my code to create the array and after this, inserts it in Firebase Database.
$scope.addf = function() {
$scope.lista.push( {
tipo: $scope.exames.texames.nome,
maximo: $scope.exames.texames.max,
minimo: $scope.exames.texames.min,
atual: '0'
});
console.log ($scope.lista);
};
$scope.remove = function(index) {
$scope.lista.splice(index,1);
};
$scope.ok = function() {
$scope.exame.lista = $scope.lista;
$scope.exames.$add($scope.exame).then(function (exameRef) {
ref.child('exames').child(exameRef.key());
toastr.success('Exame adicionado!');
$state.go('app.exames.list', {}, {reload: true});
});
};
Here's the code to update the structure:
$scope.atualizar = function () {
ref = new Firebase(FBURL);
profiles = ref.child('sexames');
$scope.sexame = $firebaseObject(ref.child('sexames').child($scope.SID.$id));
$scope.sexame.$loaded().then(function(){
console.log($scope.sexame);
$scope.sexame={
status: 'Completo',
lista: { atual: $scope.item.atual}
} ;
profiles.child($scope.SID.$id).update($scope.sexame, function() {
toastr.success('Usuario Atualizado', {progressBar: true, timeOut: '200'});
});
});
};

Find the identifier of a certain data set in firebase

I'm searching through clients invoices
These invoices are stored within the client json.
so...
clients: {
... : {
invoices: {
},
},
}
I'm doing this by this:
var ref = new Firebase(fbUrl+'/clients/'+client+'/invoices/');
ref.on("value", function(snapshot) {
var list = snapshot.val();
angular.forEach(list, function(item) {
if(item.settings.number == id)
{
console.log(item.id());
invoice.details = item;
}
})
});
Inside the "if" how do I get the unique id auto generated by Firebase? In your html your able to do $id typically.
Once you call snapshot.val(), you're just dealing with a Javascript object. See the documentation for angular.forEach. You just need to specify a second argument to the function.
angular.forEach(list, function(item, key) {
...
});

Batch Update an array in mongoose object

My Schema is as below. A student can participate in any no. of events.and each Event can have any number of students.
Student{
name:String,
age:Number,
.
.
.,
events:{
type:
[
{type:Schema.ObjectId,
ref:'Event'}
]
}
}
Event{
title:String,
desc:String,
eventDate:Date,
participants:{
type:
[{
student: {type:Schema.ObjectId,
ref:'Student'},
status : String
}]
}
}
My requirement:
Every time,I create an event, I need to push all the participants of that event inside event object. and in turn, tag the event reference inside all the participants.
My code is
function handleTeamParticipants(eventObj, participants) {
Student
.find({
$or: [{
_id: participants[0].student._id
}, {
_id: participants[1].student._id
}]
})
.populate('events events.participants events.participants.student')
.exec(function(err, students) {
var studentLength = students.length,
result = [];
var saveAll = function() {
var doc = students.pop();
Student.populate(doc, {
path: 'events.participants.student',
model: 'Student'
}, function(err, student) {
student.events.push(eventObj);
student.save(function(err, saved) {
if (err) next(err); //handle error
result.push(saved);
if (--studentLength) saveAll();
else // all saved here
{
return res.status(200).send(eventObj);
}
});
});
};
saveAll();
});
}
This code is working.
So, this way, I get only the first two participants updated and in turn added to eventobj. But I want the find query to select all the participants.student._id
Please let me know the easy way to do it.
Thanks.
I used lodash method pluck.
lodash.pluck(< arrayObj >,< attribute >);
will give the list of attribute values in the arrayObj.
studentList = lodash.pluck(pariticipants,"student");
studentIdList = lodash.pluck(studentList,"_id");

Angularfire: How to access an item by one of it's properties?

My Firebase data is organized this way:
+ myappname
+ customers
+ -JV2NQv3GmoM81zdUfTe
+ name: "Mary"
+ age: "24"
+ ...
+ -JV2N9NnItCfz5vB04RS
+ name: "John"
+ age: "32"
+ ...
+ ...
+ ...
How do I retrieve a customer by it's name?
The name is guaranteed to be unique.
This is my Customer service, currently:
app.factory('Customer', function ($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL + 'customers');
var customers = $firebase(ref);
var Customer = {
all: customers,
create: function (customer) {
return customers.$add(customer).then(function (ref) {
var customerId = ref.name();
return customerId;
});
},
set: function(customerId, customer) {
return customers.$child(customerId).$set(customer);
},
find: function (customerId) {
return customers.$child(customerId);
},
findByName: function (customerName) { // TODO...
},
delete: function (customerId) {
var customer = Customer.find(customerId);
customer.deleted = true;
customer.$on('loaded', function () {
customers.$child(customerId).$set(customer);
});
}
};
return Customer;
});
Should I scan all the customers on each findByName() call?
Or should I build something like a "secondary index"?
Please, some advice, I'm just starting... :-(
Thanks to Kato indication, and Frank van Puffelen suggestions, I did at last solve my own problem.
I did add an "index", "customersByName", to my Firebase (remembering "Disk space is cheap, user's time is not" Firebase motto... :-).
I did not follow the direction in the referred answer, because I think this solution is of more general use: it scales for multiple "indexes"...
I want to post it here, hoping it can be of any use to other people.
I would like to see comments: does this solution have possible drawbacks? Is it an advisable solution, overall, for some use case?
app.factory('Customer', function ($firebase, FIREBASE_URL) {
var ref = new Firebase(FIREBASE_URL + 'customers');
var customers = $firebase(ref);
var refByName = new Firebase(FIREBASE_URL + 'customersByName');
var customersByName = $firebase(refByName);
var Customer = {
all: customers,
create: function (customer) {
return customers.$add(customer).then(function (ref) {
var customerId = ref.name();
customersByName.$child(customer.name).$set(customerId);
return customerId;
});
},
set: function(customerId, customer) {
var oldname = customers.$child(customerId).name;
if (customer.name !== oldname) {
customersByName.$remove(oldname);
}
customersByName.$child(customer.name).$set(customerId);
return customers.$child(customerId).$set(customer);
},
find: function (customerId) {
return customers.$child(customerId);
},
findByName: function (customerName) {
return customersByName.$child(customerName);
},
delete: function (customerId) {
var customer = Customer.find(customerId);
customer.deleted = true;
customer.$on('loaded', function () {
customersByName.$remove(customer.name);
customers.$child(customerId).$set(customer);
});
}
};
return Customer;
});

How to write structured data with JSON writer?

How can I include hasOne associated model data in the JSON POST?
Structured data is required by my web API in the form of:
{
id: 1234,
name: 'Aaron Smith',
address: {
address1: '1925 Isaac Newton Sq',
address2: 'Suite 300',
city: 'Reston',
state: 'VA',
zip: 20190
}
}
#nonino
I think I know how to do it but I am also having a similar problem. I can't actually get my associations to give me the associated data. Anyway from what I have scrounged on the internet make a custom writer like this or just in the default writers getRecordData: function(record,operation)
Here is my custom writer
Ext.define('Wakanda.writer', {
extend: 'Ext.data.writer.Json',
// alternateClassName: 'SimplyFundraising.data.WakandaWriter',
alias: 'writer.wakanda',
writeAllFields: false,
getRecordData: function(record,operation) {
debugger;
Ext.apply(record.data,record.getAssociatedData());
debugger;
var isPhantom = record.phantom === true,
writeAll = this.writeAllFields || isPhantom,
nameProperty = this.nameProperty,
fields = record.fields,
data = {},
changes,
name,
field,
key;
if (writeAll) {
// console.log("getRecordData1", this, arguments);
fields.each(function(field){
if (field.persist) {
debugger;
name = field[nameProperty] || field.name;
data[name] = record.get(field.name);
} else {
}
});
} else {
changes = record.getChanges();
debugger;
// console.log("getRecordData2", this, arguments, changes);
for (key in changes) {
if (changes.hasOwnProperty(key)) {
field = fields.get(key);
name = field[nameProperty] || field.name;
data[name] = changes[key];
}
}
if (!isPhantom) {
debugger;
data[record.idProperty] = record.getId();
if(operation.action !== 'destroy'){
data[record.stampProperty] = record.get(record.stampProperty);
}
}
}
return {'__ENTITIES': [data]};
}
});
The key I think is in the getRecordData where I have a statement Ext.apply(record.data,record.getAssociatedData()); If record.getAssociatedData does indeed return your data then the Ext.apply statement will merge your current record.data with your record.getAssociatedData into 1 json file. At least this is what I hope happens. Can't test until I get my associations setup correctly.
Hope this helps,
Dan
getRecordData: function(record,operation) {
debugger;
Ext.apply(record.data,record.getAssociatedData());
debugger;

Resources