1đź‘Ť
There are several points to be adapted in your code:
1. add()
is a method of a CollectionReference
The add()
method is to be called on a CollectionReference
, not on a DocumentReference
.
Since you want the new document(s) to have a path “/restaurants/restaurant(a document which has auto generated doc id)/ my new collection” you need to do:
db.collection('restaurants').doc(doc.id).collection("my_new_collection").add()
2. You should take into account the number of restaurant docs for a user
You don’t specify if a given user can have one or more restaurants documents (in other words how many docs the db.collection('restaurants').where('ownerID', '==', user.uid)
query will return).
If, for a given user, the query returns only ONE restaurant, you could adapt your code as follows:
db.collection('restaurants').where('ownerID', '==', user.uid).get()
.then(snapshot => { //This is a QuerySnapshot
return snapshot.docs[0].ref.collection("my_new_collection").add(...);
}).then(() => {
this.menuTitle = '';
//...
}).catch(err => {
console.log(err);
})
If, on the other hand, the query may return several docs, it is better to use Promise.all()
as follows, in order to correctly chain the promises returned by the asynchronous methods:
db.collection('restaurants').where('ownerID', '==', user.uid).get()
.then(snapshot => {
const promises = [];
snapshot.forEach((doc) => {
promises.push(doc.ref.collection("my_new_collection").add(...));
})
return Promise.all(promises);
}).then(result => {
this.menuTitle = '';
//...
}).catch(err => {
console.log(err);
})
Note that, instead of using Promise.all()
you could use a batched write. One of the difference with Promise.all()
, is that a batch of writes completes atomically.