I am trying to work with an array, trying to run doc.data().includes
and doc.data().indexOf
on the array I stored on the cloud firestore, the array is the only thing that exists in the doc.
The data is arranged like this
0: example@gmail.com
1: firebase@gmail.com
2: new@gmail.com
To get to the data I just do
firebase.firestore().collection('mails').doc('emails').get().then((doc) => {
if (doc.exists) {
console.log(doc.data()); //prints the list of emails in form of array
doc.data().IndexOf(email); //error IndexOf doesn't exist
doc.data().includes(email); //error includesOf doesn't exist
}
else {
console.log('data doesn't exist');
}
});
To Get Access to doc.data().IndexOf
or doc.data().includes
or any other array related functions, just convert the doc.data()
to array like this:
var docArray = Object.values(doc.data());
docArray.includes(stringToSearchFor);
or
Object.values(doc.data()).includes(stringToSearchFor);
this will allow you to run docArray.includes
and docArray.IndexOf
. Reason for converting is that firebase returns the entire doc which is an object of objects, you can see this by console.log(doc.data()) and seeing prototype field. This happens because firestore stores the array a json object meaning the array index numbers you see are not actually index numbers, they just object keys.
meaning
0: example@gmail.com
1: firebase@gmail.com
2: new@gmail.com
where 0, 1, 2
is the index( or as it seems) and example@gmail.com, firebase@gmail.com, new@gmail.com
is value but in firestore that 0, 1, 2
is actually just keys, they are not index. So to get either the key(the numbers) or the values( the emails) we just run Object.keys(doc.data())// will return numbers
or Object.values(doc.data())//will return emails
and you will get array that you want and now you can run operations on this array.
I would suggest that you store your data in an Array and not as separate fields as shown by your Firestore database screenshot.
Your Firestore document currently contains 6 different fields and with doc.data()
you retrieve all the 6 fields in this document as one JavaScript Object: this is why the Array methods cannot work. If you store this data in one Array (ie one field of type Array) it will be ok.
You can try the following code:
const docRef = firebase.firestore().collection('mails').doc('emails');
docRef
.set({
mails: ['example@gmail.com', 'firebase@gmail.com', 'new@gmail.com'],
})
.then(() => {
return docRef.get();
})
.then((doc) => {
if (doc.exists) {
const email = 'example@gmail.com';
console.log(doc.data().mails);
console.log(doc.data().mails.indexOf(email));
console.log(doc.data().mails.includes(email));
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.