Reputation: 1405
I need to set an array for objects to firestore but only the first index of urls is getting stored. Any help in the right direction would be helpful thanks.
Code:
const object = [
{
user: 'mike',
userName: 'Mike nick',
Urls:[
{comment: "BBBBB", imageUrl: "url1"},
{comment: "BBBJvuyiu", imageUrl: "url2"},
{comment: "AAAAA", imageUrl: "url3"},
],
date: 'March 20th'
}
]
firestoreRef
.collection('users')
.doc(userId)
.collection('images')
.doc('customers')
.collection('customerExperience')
.doc(userId)
.set(object, { merge: true })
need this structure as user may continue to add more data:
it looks like this when i upload the object.
Upvotes: 0
Views: 2649
Reputation: 2368
From the Official Documentation, here's the sample code for the different data types:
let data = {
stringExample: 'Hello, World!',
booleanExample: true,
numberExample: 3.14159265,
dateExample: admin.firestore.Timestamp.fromDate(new Date('December 10, 1815')),
arrayExample: [5, true, 'hello'],
nullExample: null,
objectExample: {
a: 5,
b: true
}
};
You will need the following to create an object that contains an array of objects
let object = {
user: 'mike',
userName: 'Mike nick',
urls: {
[{comment: 'BBBBB', imageUrl: 'url1'},
{comment: 'BBBJvuyiu', imageUrl: 'url2'},
{comment: 'AAAAA', imageUrl: 'url3'}]
},
date: 'March 20th'
};
Let me know if this works for you.
Upvotes: 0
Reputation: 83058
Your const object
is actually an Array, when it should be an Object (that is not an Array).
The following should work:
const object = {
user: 'mike',
userName: 'Mike nick',
urls: [
{ comment: 'BBBBB', imageUrl: 'url1' },
{ comment: 'BBBJvuyiu', imageUrl: 'url2' },
{ comment: 'AAAAA', imageUrl: 'url3' }
],
date: 'March 20th'
};
Note the difference with your object:
const object = [
{
.....
}
]
UPDATE following your comment:
If you want to have it saved exactly the way you show in your updated question, do as follows. I am not sure however that this is the best way to save your data: as a matter of fact you are not creating an array but several fields of type "map" with the following names: 0, 1, etc.
One of the main (negative) side effect is that you will need to know all the fields names upfront in order to read them, while with a "genuine" Array field, you can loop over its values.
const object = {
0: {
user: 'mike1',
userName: 'Mike nick',
urls: [
{ comment: 'BBBBB', imageUrl: 'url1' },
{ comment: 'BBBJvuyiu', imageUrl: 'url2' },
{ comment: 'AAAAA', imageUrl: 'url3' }
],
date: 'March 20th'
},
1: {
user: 'mike2',
userName: 'Mike nick',
urls: [
{ comment: 'BBBBB', imageUrl: 'url1' },
{ comment: 'BBBJvuyiu', imageUrl: 'url2' },
{ comment: 'AAAAA', imageUrl: 'url3' }
],
date: 'March 20th'
}
};
Upvotes: 2