当我检索Firebase实时数据库快照时,它的值为 (snapshot.val())
自带密钥,无法访问文档中的数据。这是代码。
const recordExist = await admin.database().ref("order").child("live_orders").orderByChild('driver_id').equalTo(driverId)
.limitToLast(1).once('value', function (snapshot) {
console.log('Live order exisitng : ' + JSON.stringify(snapshot.val()));
return snapshot.val();
});
这是控制台日志
Live order exisitng : {
"-M4E52NNntPP5BSHp0b-":{
"customerName":"Ruwan Perera",
"customerNo":"0775886998",
"deliveryAddress":"Galle Rd, Moratuwa 10400",
"deliveryLocation":{
"latitude":6.7798672,
"longitude":79.8831725
},
"distance_to_deliver":14791,
"distance_to_pickup":788,
"driver_id":"K9HA9HfLMEZC4qR1IDbjGbSscx13",
"duration_to_deliver":2228,
"duration_to_pickup":171,
"orderNo":"order-0001",
"order_id":"-M4E52AHF4nMwis0b6Wa",
"paymentMethod":"Cash On Delivery",
"pickupAddress":"603 Kotte Rd, Sri Jayawardenepura Kotte 10100",
"pickupLocation":{
"latitude":6.8903602,
"longitude":79.9032734
},
"status":"Rejected",
"totalPayment":"1000",
"totalQuantity":"5",
"total_distance":15579,
"total_duration":342
}
}
我想访问其中的 "状态",但当我试图访问状态时,它显示为undefined.这是代码 const recordExist = await admin.database(.ref("order").child("live_orders").orderByChild(driver_id').equalTo(driverId).
你把asyncawait和回调方法混在一起,这是不推荐的。
所以,对于asyncawait,你应该做如下处理。
const dataSnapshot = await admin.database().ref("order").child("live_orders").orderByChild("driver_id").equalTo(driverId).limitToLast(1).once('value');
const status = dataSnapshot.val().status;
我们简单地调用 val()
的方法 DataSnapshot
,它提取一个JavaScript值,并获取这个JavaScript对象的状态属性。
如果你想把它转化为async函数,你可以做如下操作(根据你的具体需求进行微调)。
async function isRecordRejected(driverId) {
const dataSnapshot = await admin.database().ref("order").child("live_orders").orderByChild("driver_id").equalTo(driverId).limitToLast(1).once('value');
const status = dataSnapshot.val().status;
return (status === "Rejected" ? true : false);
}
最后,请注意,如果你想检查是否存在一个 DataSnapshot
,你应该使用 exists()
的方法。
我找到了一个解决我的问题的方法。
将值观察器附加到数据列表上,将把整个数据列表作为一个单一的快照返回,然后你可以循环访问各个子项目。
即使只有一个匹配的查询,快照仍然是一个列表;它只是包含一个单一的项目。要访问这个项目,你需要循环访问结果。
所以我的解决方案是
const existingRecords: any[] = [];
const recordExist = await admin.database().ref("order").child("live_orders").orderByChild('driver_id').equalTo(driverId).limitToLast(1).once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var childData = childSnapshot.val();
console.log('child snapshot : ' + JSON.stringify(childData));
existingRecords.push(childData);
});
});
if (recordExist !== null) {
const status = existingRecords[0].status;
if (status !== 'Rejected') {
if (status !== 'Completed') {
console.log('driver ' + driverLive.firstName + ' ' + driverLive.lastName + ' is busy right now and status is ' + status);
continue;
}
}
}
它为我工作。