Creating nested array in firebase Object - angularjs

I want to push a value to a nested array which is stored in my firebase database. The target looks like this:
I'm query the firebase database and receive snapshot. With this snapshot I want to store my changes. If i push the new value it creates me in firebase this:
How can I avoid the unique FB id and replace it with a normal index counter?
My code from the angular service:
//Save StarBewertung on Mamis
this.saveStarOnMami = function (data) {
var ref = new Firebase("https://incandescent-heat-5149.firebaseio.com/contacts")
var query = ref.orderByChild("id").equalTo(data).on("child_added", function(snapshot) {
if( snapshot.val() === null ) {
/* does not exist */
} else {
//snapshot.ref().update({"phone_fixed": '123'});
snapshot.ref().child('rateData').push(1);
}
});
}
Is there a way to get the snapshot as an $firebaseobject, manipulate it, and then save it to the Firebase DB with $save?
Thanks...

dbRef.push() will always append the data with a new UID as key.
Use dbRef.update() or dbRef.set() instead.
Example (untested)
var rateSnapshot = snapshot.child('rateData');
if( rateSnapshot.val() === null ) { // rateData key does not exist
rateSnapshot.ref().set([5]);
} else {
var rates = rateSnapshot.val(); //should be an array
rates.push(1); //append new value to the array
rateSnapshot.ref().set(rates);
}

Related

Firestore add data over an object within a document's data REACT.JS

I want to add some data on the bookChapters object, like a random id and inside of it the name of the chapters, I tried this but it doesn't work, after I add the previous data I also want to add a new object "takeAways", like the previous one, inside the random id object.
export const createNewChapter = (bookId, inputText) => {
return async dispatch => {
dispatch(createNewChapterStart());
try {
firebase
.firestore()
.doc(`Users/${bookId}/bookChapters/${inputText}`)
.onSnapshot(querySnapshot => {
//There I want to add the chapters to the firestore database
});
dispatch(createNewChapterSuccess(inputText));
} catch (error) {
dispatch(createNewChapterFail(error));
console.log(error);
}
};
};
I wanna know how to do add from scratch the bookChapters object
The database screenshot shows that the bookChapters object is a map. So to add (populate) this object you need to generate a simple JavaScript object with some properties as “key: value” pairs.
Something along these lines, making the assumption the chapter titles are in an Array:
function arrayToObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i) {
obj[i] = arr[i];
}
return obj;
}
const chapterList = ['Intro', 'Chapter 1', 'Chapter2', 'Conclusion'];
const bookChaptersObj = arrayToObject(chapterList);
firebase.firestore().doc(`Users/${bookId}`).update(bookChaptersObj);
Or, if the document does not already exist:
firebase.firestore().doc(`Users/${bookId}`).set(bookChaptersObj, {merge: true});

Doc with ObjectId Array - push value if exists, remove otherwise

I'm new to MongoDB and mongoose.
So my model holds many fields, amongst them is an Array of ObjectIDs
var modelSchema = new Schema({
//...
inner_array: [Schema.Types.ObjectId],
//...
});
What I'm trying to achieve with my query is:
Find a model by it's Id,
If the inner array contains a specific value remove it from the array.
If the value is not within the inner_array, push it
var target_id = // document id
var inner_object_id = // value to push
models.MyModel.findOne(
{_id: target_id},
function (err, model) {
// IN THIS SCOPE 'INNER_OBJECT_ID' IS UNDEFINED
// if model.inner_array contains 'inner_object_id', remove it
// otherwise, push 'inner_object_id' into model.inner_array
model.save();
res.json(model); // return modified document to client
}
);
I believe this can be written in a single findOneAndUpdate, but I can't figure out the syntax..
Thanks alot!
I believe you can achieve that using MongooseArray.pull and MongooseArray.addToSet
var target_id = // document id
var inner_object_id = // value to push
models.MyModel.findOne({
_id: target_id
}, function (err, model) {
if (model.inner_array.indexOf(inner_object_id) !== -1) {
model.inner_array.pull(inner_object_id);
} else {
model.inner_array.addToSet(inner_object_id);
}
model.save();
res.json(model); // return modified document to client
}

using query to read the last value and change it firebase angularjs 1

I have this database
service/
-KSxobYDhjUJeSvu3dC1
-Accion:"Nueva ronda"
-Codigo: 3
-dateTime: 1475284727
-notify: 0
-num_mesa: 0
-KSxobptdYSc-qrCSbyU
-Accion: "Orden cancelada"
-dateTime: 1475284728
-notify: 0
-num_mesa: 0
and then I have this code:
ref.orderByChild("notify").equalTo(1).limitToLast(1).on("child_added", function(snapshot) {
var changedPost = snapshot.val();
var mykey = snapshot.key;
if(changedPost.notify == 1 ){
var message = "New action "
console.log(serviceArray[mykey].notify);//undefined
$scope.showActionToast(message);
}
});
This code will read the last entry in the database and show a toast, notifying that a new action has been inserted in firebase. It shows the toast.
My problem is that I don't want it to show every time i reload the page.
So I thought about adding a simple flag that if it was shown in a toast, it will change notify to 0.
My problem is that I have service that returns a firebaseArray named serviceArray. When I try to access the row to change the value it says undefined. How can I change the value in the same function?
You're going to be better off simply tracking the timestamp of the last message you've shown to the user. With that you can query for messages that were added after that timestamp:
var timestampOfMostRecentlySeenMessage = null;
if (timestampOfMostRecentlySeenMessage) {
ref.orderByChild("timestamp")
.startAt(timestampOfMostRecentlySeenMessage)
.limitToLast(1)
.on("child_added", function(snapshot) {
var message = snapshot.val();
timestampOfMostRecentlySeenMessage = message.dateTime;
})
Now you just need to maintain the value of timestampOfMostRecentlySeenMessage between page reloads. You could do this in a cookie, in local storage of your browser or even in a user-specific part of your database:
var userRef = firebase.database().ref("users").child(user.uid);
userRef.child("timestampOfMostRecentlySeenMessage").set(timestampOfMostRecentlySeenMessage);
i just added a flag that declares after running the search for the first time.
ref.orderByChild("notify").equalTo(1).limitToLast(1).on("child_added", function(snapshot) {
var changedPost = snapshot.val();
var mykey = snapshot.key;
if(changedPost.notify == 1 && $scope.flag== 1 ){
var message = "New action "
console.log(serviceArray[mykey].notify);//undefined
$scope.showActionToast(message);
}
$scope.flag= 1;
});

How to Convert Fire base Child Added result Value to Json list using Ionin (angular js)

I want to convert the firebase result to JSON list (dynamially).
ref.child("USERS").child(localStorage.getItem('id')).child("ADDRESS").on("child_added", function(snapshot)
{
var data = snapshot.val();
});
I need the list like this:
$scope.AddressList =
[
{ Name: "Sampel" },
];
Instead of using child_added, use the value event to retrieve and listen to the entire node for changes.
ref.child("USERS").child(localStorage.getItem('id')).child("ADDRESS").on("value", function(snapshot) {
var data = snapshot.val();
});
This will return an object.

Getting object or array value for Auth on Firebase

I'm using angularfire 1.1.1 to store my apps objects and each object creates associated indexes. So when a user is created, that user is added to the 'users' table and then the users index table gets keyed with the UID and points to the actual user's id.
When the main state is called, I run a checkAuth() method to see if a user is signed in. If so, then I want to assign $rootScope.auth = {id:userID, role: role} etc.
The function works great in my login method but i don't know how to grab the value from my checkAuth() method. I've tried $value on both $firebaseObject and $firebaseArray, also tried to call them with [0] since there is only one id value in the table for each user's uid.
The sloppy regex is for changing the semi-colon from SimpleLogin:47 to SimpleLogin-47 for keying to the index.
Here's the code that doesn't work:
function authCheck(){
var getAuth = $firebaseAuth(Data.ref);
console.log('signed in as', getAuth.$getAuth().uid);
var uid = getAuth.$getAuth().uid.toLowerCase().replace(/'+/g, '').replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "-").replace(/^-+|-+$/g, '');
var userIndexRef = Data.ref.child('index/users/uid/'+uid);
var userIndexArray = $firebaseArray(userIndexRef);
var userIndexObject = $firebaseObject(userIndexRef);
console.log(userIndexArray, userIndexObject);
var realId = '';
angular.forEach(userIndexObject, function(key, id){
realId = id;
$rootScope.auth = realId;
return realId;
});
}
Here's the login code that does work:
function login(email, pass) {
ref.authWithPassword({email:email,password:pass}, function(error, authData){
if (error) {
console.log(error);
} else {
console.log('signed in as',authData.uid);
var uid = authData.uid.toLowerCase().replace(/'+/g, '').replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "-").replace(/^-+|-+$/g, '');
angular.forEach(Data.dataObject.index.users.uid[uid],function(id, key){
$rootScope.role = Data.dataObject.users[id].role;
$rootScope.auth = {authData:authData, id:id, role:Data.dataObject.users[id].role};
});
}
});
}
If anyone sees where I've messed up, I'll be happy to know. Here's the repo https://github.com/irthos/medviz if it helps. Thank you very much!

Resources