How do I achieve this using firebase 9 push? - javascript

I switch to firebase 9 and want to achieve following
customers
-MomOdRNzkqr9vDk_MmE:"ptwXJ7JRAASFgd3KoS2fQyQhyV613"
-Myb3b_2W-7FTlsZvXCO:"QZOQ43DGYwfu4djlZ5EjEVksOr53"
I am trying the following
const customerSelectedRef = ref(db,`/serviceProvider/${user1.uid}/moneyCollector/customers`);
const customerSelectedRefPush = push(customerSelectedRef);
set(customerSelectedRefPush, customerSelected); // not wanted to use {customerSelected} which gives key value pair under push id
How could add value directly to push id?
The old method was
firebase
.database()
.ref(`/serviceProvider/${user1.uid}/moneyCollector/customers`)
.push(customerSelected)
.then(() => {
console.log("Data set.moneyCollector cutomer added");
checkdubArray = [];
});
Where push id acts as key for customerSelected
and I try to get same result in firebase 9.
Dont want the result which I have marked as cross

You can pass the string value directly in push() along with the DatabaseReference as shown below:
const customerSelectedRef = ref(db,`/service/${user1.uid}/Collector/customers`);
await push(customerSelectedRef , "string_value") // Not object
The result would be:

Related

I'm trying to make an array with only values ​that are not contained in the other array (non-repeating)

I have an array of available users that can be invited and also another array with all joined users to the particular chat. I need to check which of the available users have joined the chat and should be listed elsewhere.
Finally, I want to get an array with only the available users who have not joined the chat.
let availablеUsers = [{id:1,name:'Dani'}, {id:2,name:'Ani'}, {id:3,name:'Marta'}]
let allUsers = [{id:2,name:'Ani'},{id:10,name:'John'}, {id:3,name:'Marta'}]
The first thing I try to do is find those who are already participating in the chat:
let joinedUsers = availablеUsers.map((user) => {
return allUsers?.find((u) => u.id === user.id);
});
And i get this : [undefined, {… Аni}, {… Marta}]
Then I try to filter the array of available users so that I remove from it those that are in the newly created array and here's the problem I don't know how to do this :/
My idea is something like that:
availablеUsers = availablеUsers.filter((user) => {
//HERE I don't know what logic to write
return joinedUsers?.map((m) => m?.id !== user.id); // this doesn't work, just an example
});
My goal is to have only those users not contained in the other remain in the availableUsers array.
In the example I have given at the end in the array should remain only {id:1,name:'Dani'}
I welcome any suggestions. If it can do it with chaining, without the extra variable for joinedUsers it would be even better!
There's no need for joinedUsers. Just use find() or some() in the filter() callback, and invert the test.
availableUsers = availableUsers.filter(user => !allUsers.some(u => u.id == user.id))
if users are uniquely identified by id you can use just a filter with a Set of known users:
let availablеUsers = [{id:1,name:'Dani'}, {id:2,name:'Ani'}, {id:3,name:'Marta'}]
let allUsers = [{id:2,name:'Ani'},{id:10,name:'John'}, {id:3,name:'Marta'}]
let joinedUsers = availablеUsers.filter(
function ({id}) {
return this.has(id);
},
new Set(allUsers.map(({id}) => id))
);
Accordingly, you can use the same to update availablеUsers in one go:
availablеUsers = availablеUsers.filter(
function ({id}) {
return !this.has(id);
},
new Set(allUsers.map(({id}) => id))
);
it's not super clear why or when you need !== vs === but the concept is: use a set and use filter instead of map when you want to filter + a Set works harder while constructed but it's blazing fast while used via has()

React JS: How to pass an array from firebase in query parameter?

I'm using multiselection in one of my parameters and I would like to know how to query those parameters like for example if
I want to query parameters that has 1 (doesn't matter if there are other values)
Value one has : 1, 2, 3
Value two has: 5, 1, 6
Value three has: 5, 6, 9
It should only bring Value one and two
I know you can do something like (for non array values):
const librosRef = db.collection('libros');
const queryRef = librosRef.where('grado', '==', '4° Grado');
and it would bring all the documents in that collection that has 4° Grado but if I try to do that while using a multiselection it doesn't bring anything.
This is what I'm trying (doesn't work for array which is what I'm trying to figure out):
const productosRef = db.collection('productosAIB');
const queryRef = productosRef.where('grado', '==', '4° Grado');
useEffect(() => {
queryRef.orderBy("precio")
.get()
.then((snapshot) => {
const tempData = [];
snapshot.forEach((doc) => {
const data = doc.data();
tempData.push(data);
});
setProductos(tempData);
});
}, []);
Example of how it gets stored in the Firebase:
And this is how it looks in the table (without the query because if I add the query it doesn't show anything )
It sounds like you're trying to query for documents based on the existence of a value in an array. These are called array membership queries in Firestore.
For this, you would use array-contains to match a single field in an array, and array-contains-any to match any value from an array.
To query based on single value in array
const queryRef = productosRef.where('grado', 'array-contains', '4° Grado');
multiple values passed in as an array
const queryRef = productosRef.where('grado', 'array-contains-any', ['4° Grado', 'next array element']);
NOTE: array-contains-any can support up to 10 comparison values.
For more information on array membership queries you can see the documentation here

Add a few more values ​to the previous array in postman

in my test i sholud compare response permission with my rolepermission_array variable in envirment
but there is diffrent , the reponse permission has 4 more permission because of it i should update my envirment
what should i do
First
in this image my response has 4 more value
Second
"authenticated",
"manage_profile",
"manage_account",
"verify_email"
i should add this values to rolepermission_array
i update my code but still get error
PreRequest
Test
Result
You can add element to array using push(element1, element2, ...)
To save array to environment, remember stringify
To get array from environment, use parse
In tab Test
const res = pm.response.json();
const per = res.data.permissions;
const rolepermission = JSON.parse(pm.environment.get("rolepermission_array"));
rolepermission.push("authenticated", "manage_profile", "manage_account", "verify_email");
pm.test("check permissions", () => {
pm.expect(per).eql(rolepermission);
})

Multiple Firebase listeners in useEffect and pushing new event into state

I want to retrieve a list of products in relation to the user's position, for this I use Geofirestore and update my Flatlist
When I have my first 10 closest collections, I loop to have each of the sub-collections.
I manage to update my state well, but every time my collection is modified somewhere else, instead of updating my list, it duplicates me the object that has been modified and adds it (updated) at the end of my list and keep the old object in that list too.
For example:
const listListeningEvents = {
A: {Albert, Ducon}
B: {Mickael}
}
Another user modified 'A' and delete 'Ducon', I will get:
const listListeningEvents = {
A: {Albert, Ducon},
B: {Mickael},
A: {Albert}
}
And not:
const listListeningEvents = {
A: {Albert},
B: {Mickael},
}
That's my useEffect:
useEffect(() => {
let geoSubscriber;
let productsSubscriber;
// 1. getting user's location
getUserLocation()
// 2. then calling geoSubscriber to get the 10 nearest collections
.then((location) => geoSubscriber(location.coords))
.catch((e) => {
throw new Error(e.message);
});
//Here
geoSubscriber = async (coords) => {
let nearbyGeocollections = await geocollection
.limit(10)
.near({
center: new firestore.GeoPoint(coords.latitude, coords.longitude),
radius: 50,
})
.get();
// Empty array for loop
let nearbyUsers = [];
// 3. Getting Subcollections by looping onto the 10 collections queried by Geofirestore
productsSubscriber = await nearbyGeocollections.forEach((geo) => {
if (geo.id !== user.uid) {
firestore()
.collection("PRODUCTS")
.doc(geo.id)
.collection("USER_PRODUCTS")
.orderBy("createdDate", "desc")
.onSnapshot((product) => {
// 4. Pushing each result (and I guess the issue is here!)
nearbyUsers.push({
id: product.docs[0].id.toString(),
products: product.docs,
});
});
}
});
setLoading(false);
// 4. Setting my state which will be used within my Flatlist
setListOfProducts(nearbyUsers);
};
return () => {
if (geoSubscriber && productsSubscriber) {
geoSubscriber.remove();
productsSubscriber.remove();
}
};
}, []);
I've been struggling since ages to make this works properly and I'm going crazy.
So I'm dreaming about 2 things :
Be able to update my state without duplicating modified objects.
(Bonus) Find a way to get the 10 next nearest points when I scroll down onto my Flatlist.
In my opinion the problem is with type of nearbyUsers. It is initialized as Array =[] and when you push other object to it just add new item to at the end (array reference).
In this situation Array is not very convenient as to achieve the goal there is a need to check every existing item in the Array and find if you find one with proper id update it.
I think in this situation most convenient will be Map (Map reference). The Map indexes by the key so it is possible to just get particular value without searching it.
I will try to adjust it to presented code (not all lines, just changes):
Change type of object used to map where key is id and value is products:
let nearbyUsersMap = new Map();
Use set method instead of push to update products with particular key:
nearbyUsersMap.set(product.docs[0].id.toString(), product.docs);
Finally covert Map to Array to achieve the same object to use in further code (taken from here):
let nearbyUsers = Array.from(nearbyUsersMap, ([id, products]) => ({ id, products }));
setListOfProducts(nearbyUsers);
This should work, but I do not have any playground to test it. If you get any errors just try to resolve them. I am not very familiar with the geofirestore so I cannot help you more. For sure there are tones of other ways to achieve the goal, however this should work in the presented code and there are just few changes.

Using Firebase Push key as Key in Second Push

I'm trying to add two related items to my Firebase database. I want to push one item, then get that item's newly created key and use it as the key for the second item in a different tree. I've tried querying the database to get the last key created and using it as the key for the second push, but it's still just generating a new key for it. Here's the code that I'm using:
save: function() {
if (this.$.document.isNew && (this.editableCard.title || this.editableCard.body)) {
return this.$.document.save(this.cardsPath).then(function() {
this.$.document.reset();
var sceneRef = firebase.database().ref().child(this.cardsPath);
var scene = sceneRef.orderByKey().limitToLast(1);
var sceneKey = scene.key;
this.$.document.save('/documents/', sceneKey);
}.bind(this));
}
return Promise.resolve();
}
(I'm using Polymer, and my starting point is the note-app demo for Polymerfire).
Any ideas on how I can retrieve the new key of the first push and use it for the second push? Thanks!
EDIT
I found the answer in Firebase's documentation for Reading and Writing to the database for Web. Link
push() returns a DatabaseReference immediately. You can ask that reference what its key is, using getKey(), then use that string to update another location in your database.
You can access the key property on the original database reference and use that as the key for the second one, like so:
let firstObjRef = firebase.database().ref('/first/path/).push(firstObj, (error) => {
videoObj["roomUploadedTo"] = this.roomName;
var updateObj = {};
updateObj[videoObjRef.key] = videoObj;
firebase.database().ref('/second/path/').update(updateObj).then( (e) => {
console.log('update went through. booyah! ' + e);
})

Categories