How to get property name in firebase - angularjs

I have this in firebase.
{
'users':
{
'random1':
{
'name': 'David'
}
},{
'random2':
{
'name': 'Dan'
}
}
}
How to list out random1 and random2 using angularFire.
What I want to do is to get random1 and random2 then pass it url for later remove.
Example
ref.child('users/' + therandomidhere);
$scope.remove = userRef.remove();

I'm not exactly sure what you're trying to do, but you can remove a property in an object by simply setting it to null. For example:
function MyController($scope, angularFire) {
angularFire(ref, $scope, "users", {}).then(function() {
// You can delete random1 by doing:
$scope.users["random1"] = null;
// Or:
delete $scope.users["random1"];
// You can enumerate all the keys by:
for (var key in $scope.users) {
console.log(key);
}
});
}
Hope this helps!

Related

excluding from an object angular ng-change

Hello guys i am trying to clear my ng-model when i fire my change function but my problem that i don't want to delete all i want to exclude one item in the object.
function change() {
if (vm.location.type) {
angular.forEach(vm.location, function (value, index) {
delete vm.location;
});
}
}
so i don't want to delete the
vm.location.type
my
vm.location
has
vm.location.boundaries;
vm.location.region;
vm.location.address;
vm.location.name;
vm.location.nonVisitingRadius;
vm.location.visitingRadius;
See the code below,
var obj = { a:123, b:123, c:123 }
delete obj.a;
Hence obj will be like this {b:123, c:123}
Note: Dont need any for loop to delete property from object
Updated Answer:
var obj= {
a: 'aaa',
b: 'bbb',
c: 'ccc',
d: 'ddd'
};
var removeObj = function(obj, props) {
for(var i = 0; i < props.length; i++) {
if(obj.hasOwnProperty(props[i])) {
delete obj[props[i]];
}
}
};
removeObj (obj, ["a", "d"]);
i don't know if i understand correctly what you're asking, but if you want to clear all the fields of your object preserving only type and preserving the reference of the object with plain javascirpt (no libraries), loop over the fields and check if the i field is equal to type.
for(var i in model.location){
if(i !== 'type')
delete model[i];
}
with underscore.js you could define a default model like:
var defaultModel = {
location: {
region: '',
address: '',
name: '',
nonVisitingRadius: '',
visitingRadius: '',
type: 'defaultvalue'
}
}
and when ng-change is triggered inside the function
_.extend(model, defaultModel);
that will keep the default value for type and clear all the others.
You can do it this with a temporary object :
let tempLocation = {};
tempLocation.type = $scope.location.type;
$scope.location = tempLocation;

Can't get Firebase reference to ID to define current user

I think I am getting my keys, arrays, values and IDs mixed up here but can't seem to figure it out.
I want a way to get the current user in a ProfileCtrl controller. This is my current implementation using promises, $waitForAuth and once. But I am not sure if implementing currently.
var user = "";
var key = "";
var uids = Users.allUIDs();
console.log(uids);
Auth.$waitForAuth().then(function () {
var uid = Auth.$getAuth().uid;
console.log(uid);
for (var i = 0; i < uids.length; i++) {
console.log(uids[i].value().toString());
if (uids[i].value() == uid) {
var userKeyRef = new Firebase(firebaseUrl + uids + uids[i]);
userKeyRef.once('value').then(function(snapshot) {
key = snapshot.val();
}).then(function(){
user = new Firebase(firebaseUrl + users).child(key).val();
});
console.log(user);
console.log('User exists')
break;
}
}
$scope.user =user;
}).catch(function (error) {
console.log(error);
})
I do a check of the uids in an array, and if they match the authenticated user, I get the key from within the uids array and use that key to find the user object in the users array. Here is my database:
{
"uids" : {
"7d34fb85-813c-4586-857e-f062aed67f32" : {
"-KDQDk5vwJXmFngwI7iQ" : {
"registered" : true
}
}
},
"users" : {
"-KDQDk5vwJXmFngwI7iQ" : {
"email" : "random#gmail.com",
"firstname" : "Random",
"lastname" : "Person",
"uid" : "7d34fb85-813c-4586-857e-f062aed67f32"
}
}
}
For a clearer example, when I console.log the uids as it is returned from my service, it looks like:
Which means the uids are coming through?
Here is my code to get the uids:
app.factory('Users', ['$firebaseArray','$firebaseObject', 'Auth', function ($firebaseArray, $firebaseObject, Auth) {
var ref = new Firebase("https://urlformyapp.firebaseio.com");
var users = $firebaseArray(ref.child('users'));
var uids = $firebaseArray(ref.child('uids'));
return {
all: function () {
return users;
},
allUIDs: function () {
return uids;
},
get: function (id) {
// Simple index lookup
return users[id];
}
}
}])
Could someone tell me what is going wrong? Why does uids[i].value.toString() not print anything? Is there anything wrong with my code logic given the structure of my DB?

Joining data between paths based on id using AngularFire

I am currently working on an app using firebase and angularJS (ionic). Basically this is a car management app, so you have people sharing their cars with others. I tried to structure the data as flat as possible to be efficient. My issue here is that if without problem I can display the list of the car_id of the different cars shared with the logged user, I can't find a way to display the list of cars shared with the user displaying the year and the model.
Thank you in advance for your help !
{
"rules": {
"users": {
".write": true,
"$uid": {
".read": "auth != null && auth.uid == $uid"
},
"cars": {
"car_id":true,
"role":true // Owner, borower...
}
},
"cars": {
"car_id":true,
"model":true,
"year":true
}
}
}
carapp.controller("carsController", function($scope, $firebaseObject, $ionicPopup, $ionicHistory) {
$ionicHistory.clearHistory();
$scope.list = function() {
frbAuth = frb.getAuth();
if(frbAuth) {
var userObject = $firebaseObject(frb.child("users/" + frbAuth.uid));
userObject.$bindTo($scope, "user");
$scope.cars = frb.child("cars");
}}
$scope.createCar = function() {
$ionicPopup.prompt({
model: 'Create a new car',
inputType: 'text'
})
.then(function(result) {
if(result !== "") {
var newCar = $scope.cars.push({
model: result
})
var newCarId = newCar.key();
$scope.user.cars.push({car_id: newCarId, role: "owner" });
} else {
console.log("Action not completed");
}
});
}
});
<div class="list">
<a ng-repeat="car in user.cars" >
<h2>{{car.car_id}}</h2> ----> works fine !
<h2>{{car.model}}</h2> ----> How to get this working ?
<h2>{{car.year}}</h2> ----> How to get this working ?
</a>
</div>
In the users/ path, begin by storing the list of cars by index, instead of in an array. So your structure would be:
{
"users": {
"kato": {
"cars": {
"DeLorean": true
}
}
},
"cars": {
"DeLorean": {
model: "DeLorean",
year: "1975"
}
}
}
To join this using AngularFire, you have several approaches available. An AngularFire-only solution might look like this, taking advantage of $extend:
app.factory('CarsByUser', function($firebaseArray) {
return $firebaseArray.$extend({
$$added: function(snap) {
return new Car(snap);
},
$$updated: function(snap) {
// nothing to do here; the value of the index is not used
},
$$removed: function(snap) {
this.$getRecord(snap.key()).destroy();
},
// these could be implemented in a manner consistent with the
// use case and above code, for simplicity, they are disabled here
$add: readOnly,
$save: readOnly
});
var carsRef = new Firebase(...).child('cars');
function Car(snap) {
// create a reference to the data for a specific car
this.$id = snap.key();
this.ref = carsRef.child(this.$id);
// listen for changes to the data
this.ref.on('value', this.updated, this);
}
Car.prototype.updated = function(snap) {
this.model = data.model;
this.year = data.year;
}
Car.prototype.destroy = function() {
this.ref.off('value', this.meta, this);
};
function readOnly() { throw new Error('This is a read only list'); }
});
app.controller('...', function($scope, CarsByUser, authData) {
// authenticate first, preferably with resolve
var ref = new Firebase(...).child(authData.uid);
$scope.cars = CarsByUser($scope);
});
For a more sophisticated and elegant approach, one could utilize NormalizedCollection and pass that ref into the AngularFire array:
app.controller('...', function($scope, $firebaseArray) {
var ref = new Firebase(...);
var nc = new Firebase.util.NormalizedCollection(
ref.child('users/' + authData.uid),
ref.child('cars')
)
.select('cars.model', 'cars.year')
.ref();
$scope.cars = $firebaseArray(nc);
});

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");

Nodejs async data duplication

I'm having some problems with one async process on nodejs.
I'm getting some data from a remote JSON and adding it in my array, this JSON have some duplicated values, and I need check if it already exists on my array before add it to avoid data duplication.
My problem is when I start the loop between the JSON values, the loop call the next value before the latest one be process be finished, so, my array is filled with duplicated data instead of maintain only one item per type.
Look my current code:
BookRegistration.prototype.process_new_books_list = function(data, callback) {
var i = 0,
self = this;
_.each(data, function(book) {
i++;
console.log('\n\n ------------------------------------------------------------ \n\n');
console.log('BOOK: ' + book.volumeInfo.title);
self.process_author(book, function() { console.log('in author'); });
console.log('\n\n ------------------------------------------------------------');
if(i == data.length) callback();
})
}
BookRegistration.prototype.process_author = function(book, callback) {
if(book.volumeInfo.authors) {
var author = { name: book.volumeInfo.authors[0].toLowerCase() };
if(!this.in_array(this.authors, author)) {
this.authors.push(author);
callback();
}
}
}
BookRegistration.prototype.in_array = function(list, obj) {
for(i in list) { if(list[i] === obj) return true; }
return false;
}
The result is:
[{name: author1 }, {name: author2}, {name: author1}]
And I need:
[{name: author1 }, {name: author2}]
UPDATED:
The solution suggested by #Zub works fine with arrays, but not with sequelize and mysql database.
When I try to save my authors list on the database, the data is duplicated, because the system started to save another array element before finish to save the last one.
What is the correct pattern on this case?
My code using database is:
BookRegistration.prototype.process_author = function(book, callback) {
if(book.volumeInfo.authors) {
var author = { name: book.volumeInfo.authors[0].toLowerCase() };
var self = this;
models.Author.count({ where: { name: book.volumeInfo.authors[0].toLowerCase() }}).success(function(count) {
if(count < 1) {
models.Author.create(author).success(function(author) {
console.log('SALVANDO AUTHOR');
self.process_publisher({ book:book, author:author }, callback);
});
} else {
models.Author.find({where: { name: book.volumeInfo.authors[0].toLowerCase() }}).success(function(author) {
console.log('FIND AUTHOR');
self.process_publisher({ book:book, author:author }, callback);
});
}
});
// if(!this.in_array(this.authors, 'name', author)) {
// this.authors.push(author);
// console.log('AQUI NO AUTHOR');
// this.process_publisher(book, callback);
// }
}
}
How can I avoid data duplication in an async process?
This is because you are comparing different objects and result is always false.
Just for experiment type in the console:
var obj1 = {a:1};
var obj2 = {a:1};
obj1 == obj2; //false
When comparing objects (as well as arrays) it only results true when obj1 links to obj2:
var obj1 = {a:1};
var obj2 = obj1;
obj1 == obj2; //true
Since you create new author objects in each process_author call you always get false when comparing.
In your case the solution would be to compare name property for each book:
BookRegistration.prototype.in_array = function(list, obj) {
for(i in list) { if(list[i].name === obj.name) return true; }
return false;
}
EDIT (related to your comment question):
I would rewrite process_new_books_list method as follows:
BookRegistration.prototype.process_new_books_list = function(data, callback) {
var i = 0,
self = this;
(function nextBook() {
var book = data[i];
if (!book) {
callback();
return;
}
self.process_author(book, function() {
i++;
nextBook();
});
})();
}
In this case next process_author is being called not immediately (like with _.each), but after callback is executed, so you have consequence in your program.
Not sure is this works though.
Sorry for my English, I'm not a native English speaker

Resources