Some reason, I just am not getting it. I want to add a new document to a sub-collection. Here is my layout as follows:
Users----------- Collection
UID----------- Document
Lists------- Collection
Category-- Document
Category-- Document
...--
For the documents in the "Lists", I want to add a Doc to Lists. The Doc is custom named.
I've tried the following:
async function AddCategory (category) {
return new Promise((resolve, reject) => {
const uid = auth.currentUser.uid
console.log(`UID: ${uid}`)
setDoc(doc(db, 'users', uid, 'lists', category), {
name: 'Johnny Doey'
}).then((res) => {
resolve(res)
}).catch((err) => {
reject(err)
})
})
}
This does not seem to work. The error I am receiving is 'Undefined'. I almost feel like there is something simple I am missing.... I've checked my auth rules. Everything checks out. Tried to test with hard strings in place of my variables, still no luck...
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId}/{documents=**} {
allow read, write: if request.auth != null && request.auth.uid == userId
}
}
}
now, the firestore data shows the initial user (UID) document to be italicized,
Even though non-existent ancestor documents appear in the console, they do not appear in queries and snapshots. You must create the document to include it in query results.
What in the heck...
Could someone please overlook this? Thanks!
CodePudding user response:
According to this post:
"When you create a reference to a subcollection using a document id like this:
db.collection('coll').doc('doc').collection('subcoll')
If document id doc doesn't already exist, that's not a problem at all. In fact, after adding documents to subcoll, doc will appear in the Firebase console in italics, indicating that it doesn't exist."
What you can do is: First, create a setDoc()
for collection "users" with its own document (whether auto-generated or manually coded), second, you can input your setDoc()
query: setDoc(doc(db, 'users', uid, 'lists', category)...
.
For a better visualisation, here's a sample code:
setDoc(doc(db, 'users', uid), {
name: 'Johnny Doey'
}).then(() => {
setDoc(doc(db, 'users', uid, 'lists', category), {
// some additional inputs here...
})
}).catch((e) => {
console.log(e)
})
For additional reference, you can check, Non-existent ancestor documents.
CodePudding user response:
Well - it works. I think one of the issues I was facing was altering the generated users.
My fix was to delete the users, and build it from scratch. That seemed to solve it for me. Not sure what exact constraints the generated user collection/doc has, but it seems it does have some restrictions tied into it.