jsonfirebasegoogle-cloud-firestoregeopointsgeofirestore

json format for geopoint in firestore document


I am able to save the below json data to the firestore database successfully through node. I want to save the 'GeoPoint' to the firestore database in the json format, which I am not able to figure out how should I write in the json file below.

 [ {     "itemID": "MOMOS_V_101",   
         "itemName": "Sangai Momos",   
         "itemPriceHalf": 70,   
         "itemPriceFull": 130,    
         "hasImage": false,     
         "itemCategory": "momos_v",   
         "itemType": "v"  
  } ] 

Please provide the format how the GeoPoint should be there in the json file to be stored in the firestore database.

Code To Upload bulk JSON Files to firestore database

var admin = require("firebase-admin");

var serviceAccount = require("./service_key.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "YOUR_PROJECT_LINK"
});

const firestore = admin.firestore();
const path = require("path");
const fs = require("fs");
const directoryPath = path.join(__dirname, "files");

fs.readdir(directoryPath, function(err, files) {
  if (err) {
    return console.log("Unable to scan directory: " + err);
  }

  files.forEach(function(file) {
    var lastDotIndex = file.lastIndexOf(".");

    var menu = require("./files/" + file);

    menu.forEach(function(obj) {
      firestore
        .collection(file.substring(0, lastDotIndex))
        .doc(obj.itemID)
        .set(obj)
        .then(function(docRef) {
          console.log("Document written");
        })
        .catch(function(error) {
          console.error("Error adding document: ", error);
        });
    });
  });
});

The complete code to write the json files is available at this link here

https://drive.google.com/file/d/1n_O_iKJWM5tR3HK07Glq6d65XAezEKLf/view


Solution

  • let's consider your Json has geopoint field like below,

    {     
         "itemID": "MOMOS_V_101",   
         "itemName": "Sangai Momos",   
         "itemPriceHalf": 70,   
         "itemPriceFull": 130,    
         "hasImage": false,     
         "itemCategory": "momos_v",   
         "itemType": "v",
         "geopoint": {
             "lat": 1,
             "long": 1
         }
    }
    

    to parse this as Firestore Geopoint, you have to change your iterator like below

    menu.forEach(function(obj) {
          obj.geopoint = new admin.firestore.GeoPoint(obj.geopoint.lat, obj.geopoint.long);
    
          firestore
            .collection(file.substring(0, lastDotIndex))
            .doc(obj.itemID)
            .set(obj)
            .then(function(docRef) {
              console.log("Document written");
            })
            .catch(function(error) {
              console.error("Error adding document: ", error);
            });
        });
    

    The above parser modifies the geopoint map field into Firestore Geopoint before write.