Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestorefirebase-console

How to manually add a document to a collection in Firestore database?


I have a quite simple database in Firestore (geographic name, lat and Lon). The database is very static and I only need to add or remove a record (document) once a while. How can I add a record manually to the collection, with the same fields as the other documents? When I press "Add document" the console asks me to input each field (see screenshot). enter image description here


Solution

  • The following HTML page will allow you to write to your spots Firestore collection.

    You need to adapt the fields, of course, as well as the Firebase config.

    If you want to authenticate, just add two extra fields e.g. Username and Password and use the signInWithEmailAndPassword() method. (I can adapt the page if you want).

    You can host this page in Firebase hosting for example, taking advantage of the SSL Certificate. Or you can simply save it on your computer and open it with a browser (not HTTPS in this case, but a good way to test).

    <!DOCTYPE html>
    <html>
      <head>
        <title>Firebase Form</title>
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
        <!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
        <script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-app.js"></script>
    
        <!-- Add Firebase products that you want to use -->
        <script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js"></script>
        <script src="https://www.gstatic.com/firebasejs/6.0.2/firebase-auth.js"></script>
      </head>
    
      <body>
        <div>
          <p>Name:</p>
    
          <input type="text" placeholder="Name" id="name" />
    
          <p>City:</p>
    
          <input type="text" placeholder="City" id="city" />
    
          <br /><br />
          <input type="submit" value="submit" class="submit" id="submit" />
        </div>
    
        <script>
          $(document).ready(function() {
            // Initialize Firebase
            var config = {
              apiKey: 'xxxxxxxxxxxxx',
              authDomain: 'xxxxxxxxxxxxx',
              databaseURL: 'xxxxxxxxxxxxx',
              projectId: 'xxxxxxxxxxxxx'
            };
    
            firebase.initializeApp(config);
    
            var database = firebase.firestore();
    
            $('#submit').on('click', function() {
              var nameValue = $('#name').val();
              var cityValue = $('#city').val();
    
              var dataObject = {
                name: nameValue,
                city: cityValue
              };
    
              database.collection('spots').add(dataObject);
            });
          });
        </script>
      </body>
    </html>