firestore文档中地理点的json格式

问题描述

我能够通过 node.js 成功地将以下 json 数据保存到 firestore 数据库中。我想以json格式将'GeoPoint'保存到firestore数据库中,我无法弄清楚我应该如何在下面的json文件中写入。

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

请提供要存储在 Firestore 数据库中的 json 文件中 GeoPoint 应如何存在的格式。

将批量 JSON 文件上传到 Firestore 数据库代码

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);
        });
    });
  });
});

编写 json 文件的完整代码可在此链接中获得

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

解决方法

让我们考虑一下您的 Json 具有如下所示的地理点字段,

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

要将其解析为 Firestore Geopoint,您必须像下面这样更改迭代器

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);
        });
    });

上述解析器在写入前将 geopoint 映射字段修改为 Firestore Geopoint