📜  firestore v9 addDoc 和 setDoc collection() doc() - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:02:53.632000             🧑  作者: Mango

代码示例1
// creates the root collection with some data. 
  ( async () => {
    let collRef = await collection(db  , "users");  // returns a collection ref. ie. creates one if one does not exist. 
    let inputObject = { name : "trying to create a collection"}
    await addDoc(collRef , inputObject , { merge : true})
    console.log("collection and its document added now ");
  })()

  // using setDoc and doc() to create a document ie. we give it a name/id 
  ( async() => {
    let docRef = await doc( db , "users/newDoc" ) // create this document newDoc at this path
    await setDoc( docRef , { name : "firstDocument"});
    console.log("first document set inside the users collection");
  })


  // using addDoc and collection() to create a doc ie. we make firebase give the document an autogenerated id/name
  ( async() => {
    let collRef = await collection( db , "users");
    await addDoc( collRef , { name : "doc made using collRef and addDoc() function"} );
    console.log("I finally understand how collection() works and what is its purpose");
  })

  // creating a subcollection inside the firstDocument document
  (async() => {
    // will crate a new collection inside j1hxFeD....... document, call it myCollectionName and return its ref
    let collRef = await collection( db , "users/firstDocument/myCollectionName");
    await addDoc( collRef , { name : "unnamed collection. firebase has chosen its name"})
    console.log("a new coll has been created");
  });