当我的数据库没有等于equalTo()的任何匹配结果时,我需要处理这种情况。目前,以下代码仅在我有匹配项的情况下返回,如果没有匹配项,则根本不返回。请告知如何处理?
function getActivitySurvey(pin) {
return new Promise((resolve, reject) => {
var ref = admin.database().ref("activity-survey");
ref.orderByChild("pin").equalTo(pin.toString()).once('child_added')
.then((snapshot) => {
if (snapshot) {
resolve(snapshot);
} else {
reject(new Error('No ActivitySurvey'));
}
}).catch( () => {
reject(new Error('No snapshot'));
})
})
}
编辑: 此后,我修改了代码,使其看起来如下所示,如果指定了数据库中不存在的pin值,则唯一会输出到控制台的行是'getActivitySurvey',该函数最终会超时但从不返回:
function getActivitySurvey(pin) {
return new Promise((resolve, reject) => {
console.log('getActivitySurvey')
var ref = admin.database().ref("activity-survey");
ref.orderByChild("pin").equalTo(pin.toString()).once('child_added').then((snapshot) => {
console.log('have snapshot')
if (snapshot.exists()) {
resolve(snapshot);
} else {
console.log('Rejecting ActivitySurvey')
reject('error');
}
}).catch( (err) => {
console.log('Caught error')
reject('err');
})
})
}
答案 0 :(得分:2)
您无法检测到仅存在child_added
侦听器的孩子是否存在。您需要为此使用value
侦听器。
例如:
ref.orderByChild("pin").equalTo(pin.toString())
.once('child_added')
.then((snapshot) => {
resolve(snapshot);
});
ref.orderByChild("pin").equalTo(pin.toString()).limitToFirst(1)
.once('value')
.then((snapshot) => {
if (!snapshot.exists()) {
reject(new Error('No ActivitySurvey'));
}
});
或仅包含一个查询:
ref.orderByChild("pin").equalTo(pin.toString()).limitToFirst(1)
.once('value')
.then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(child) { // will loop only once, since we use limitToFirst(1)
resolve(child);
});
}
else {
reject(new Error('No ActivitySurvey'));
}
});