0

I think this is not right, or i am the one not doing it well, so when i add a new document to the firestore collection, i can use the ref to get the id, but when i pass a wrong collection name, I still get the same response, why isn't firestore throwing an error.

async function addDoc(collection, data) {
    try {
        const db = admin.firestore();
        const ref = await db.collection(collection).doc() //add(data);
        ref.set(data);
        console.log("Document successfully added!", ref);
    }
    catch (err) {
        console.log("Error adding document: ", err);
    }
}

i want to know why this is behaving like this, and how to detect if the new document was created. Thanks

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user15317824
  • 370
  • 6
  • 15
  • 1
    iirc if you add data to a collection which doesn't exist (i.e. "wrong collection name") the collection will be implicitly created – Paul S. Dec 04 '21 at 01:58
  • how is that a good design option? i never taught of that and that sucks, why will I want something like this? – user15317824 Dec 04 '21 at 02:08

1 Answers1

0

Collections are created on demand, when you first write a document to them. So what you call "a wrong collection name" Firestore is likely interpreting that is an instruction to create a new collection with that name.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Hi frank, but i think that show generally throws an error or something, letting the client know that the collection does not exist, but it has been created. because how do you easily how this in an app, without doing additional call to check if that collection exitst – user15317824 Dec 04 '21 at 11:43
  • There is no way to do this without an extra call. Creating (or deleting) a collection is not considered a relevant operation (e.g. you're not charged for collections), so there are no events for them. --- If you want to check whether a collection exists, you'll typically read its contents with a `limit(1)`. – Frank van Puffelen Dec 04 '21 at 16:39
  • @user15317824 if this data is coming from a client, you'll need to validate it before passing it forward to a database or you're open to an injection attack; for the collection name this could be a hard-coded array of "known good" collections, or a 1-time call at app start to find collection names which you then validate against. You probably also want to validate `data` too so a user can't upload random/megabytes of data – Paul S. Dec 05 '21 at 00:06