如何将云firestore字段值传递给节点js中的新变量?

时间:2018-03-28 09:26:10

标签: javascript node.js google-cloud-firestore

我在index.js中有一个名为var lat和var long的新变量。为了获得firebase值,我使用了这段代码

  var lat;
  var long;

 var cityRef = 
db.collection('UsersCurrentBookings').doc('3Xg6ujHMINeElzdOD3JypcZBMHw2');
var getDoc = cityRef.get()
.then(doc => {
    if (!doc.exists) {
        console.log('No such document!');
    } else {
        console.log('Document data:', doc.data());

    }
})
.catch(err => {
    console.log('Error getting document', err);
});

我的控制台输出:

文件资料:{city:'Chennai',

国家:'印度',

时间:'10:35:57',

日期:'2018-03-28',

令牌:'deFFa4dBPlQ:APA91bF7hTjsSkk-l6fLaI939W0ISe2olO18OjCUZu4N9URr9QK44XBIyWyC1L9Vui1cawGkFaSV1M2yDG4ASJyeCtrwGyal0GmIgdciZeGVmNSUnvyddTLUPAxQlAsjpAHTJy4Lwqt',

地址:'Sri Aravinthar St,Sholinganallur,Chennai,Tamil Nadu 600119,India',

Currentlat:'12 .8710994',

Currentlong:'80 .2225558',

我希望将控制台输出值currentlat和currentlong值传递给lat和long的新变量。

从UsersCurrentBookings db获取值后,如何将值插入db.collection(DriversCurrentBookins)和参数值lat,long和token。

任何帮助将不胜感激!在此先感谢!!!

2 个答案:

答案 0 :(得分:2)

您可以直接访问JSON响应中的数据,如果需要,您也可以使用Javascript Global函数parseFloat();

将数据解析为Float类型
var lat = parseFloat(doc.data().Currentlat);
var lng = parseFloat(doc.data().Currentlong);

****的更新 ****

要向Mongo数据库添加数据,可以使用

等库

MongooseJS// This uses a model based structure, can be a little difficult to understand at first.

MongoJS

**** 更新忽略上一个 ****

const tokenField = data.getData().token
const ref = db.collection().doc(tokenField);

var jsonData = {
    'lat' : lat,
    'lng' : lng
}

ref.set(jsonData);

答案 1 :(得分:0)

将set data调用到usercurrentbooking collection db

var cityRef = 
 db.collection('UsersBookingRequest').doc('9DjekLkfFmTeLfkyZQAeezVriv02');
 var getDoc = cityRef.get()
.then(doc => {
    if (!doc.exists) {
        console.log('No such document!');
    } else {
        console.log('Document data:', doc.data());
        lat = doc.data().Currentlat;
        long = doc.data().Currentlong;
        UID = doc.data().UID;
        // token = doc.data().token;
        address = doc.data().address;
        date = doc.data().date;
        time = doc.data().time;

        console.log(lat);
        console.log(long);
        console.log(UID);
        // console.log(token);
        console.log(address);
        console.log(date);
        console.log(time);

        var data = {

                 lat: lat,
                 long: long,
                 UID: UID,
                 address: address,
                 date: date,
                 time: time
                 // token: token


                    };

                // Add a new document in collection "cities" with ID 'LA'
        var setDoc = 
 db.collection('DriversCurrentBookings').doc(doc.data().UID).set(data);

    }
})
.catch(err => {
    console.log('Error getting document', err);
});