【发布时间】:2020-02-29 06:25:15
【问题描述】:
当我使用.where() 查询文档时,我无法提取子集合。我不断收到错误:
TypeError: collectionData.where(...).collection is not a function
如果我使用标准的.doc(),它可以工作,.where() 不能工作。
hotels 是主集合中每个文档的子集合。 hotelCollection 假设将提取的数据通过要解析和执行的类传递。
index.js
exports.hotels = functions.https.onRequest((req,res) => {
cors(req, res, () => {
const countryCode = req.url.replace('/', '').toUpperCase();
const hotelCollection = collectionData.where('countryCode', '==', 'VN').collection('hotels');
switch (req.method) {
case 'GET':
Hotels.list(hotelCollection, req, res);
break;
case 'POST':
Hotels.create(hotelCollection, req, res);
break;
default:
res.status(405).send({error: 'An error occurred!'});
break;
}
})
});
hotel.js
let admin = require('firebase-admin');
class Hotels {
static list(hotelCollection, req, res) {
let hotelData = [];
return hotelCollection.collection('hotels').get()
.then(hotels => {
hotels.forEach(hotel => {
hotelData.push(hotel.data());
});
return hotelData;
})
.then(hotelData => {
return res.status(200).send(hotelData);
})
.catch(err => {
return res.status(404).send('Error finding hotel for this country: ' + err);
});
}
static create(hotelCollection, req, res) {
return hotelCollection.add(req.body)
.then(result => {
return res.status(200).send('Hotel has been added!');
})
.catch(err => {
return res.status(404).send('Error adding hotel for this country: ' + err);
});
}
}
module.exports = Hotels;
【问题讨论】:
-
错误消息告诉您
where()不返回具有称为collection()的方法的对象。它返回一个尚未执行的 Query 对象。我不清楚你希望这段代码实际做什么,因为我们看不到数据库中的数据,我们看不到Hotel上的函数实现,我们不知道应该做什么是它应该产生的响应。 -
@DougStevenson 我已经用更多上下文更新了这个问题
标签: javascript firebase google-cloud-firestore