我有以下获取请求的代码:
app.get('/getPetByOwner', async (req, res) => {
try {
const { ownerId } = req.query;
if (!ownerId) {
return res.status(400).json({ error: 'OwnerId is required in the query parameters.' });
}
const mascotasCollection = await admin.firestore().collection('pets').where('owner', '==', ownerId).get();
if(mascotasCollection.empty) return res.status(404).json({error:"pets not found for the provided user"});
const mascotasData = [];
mascotasCollection.forEach((doc) => {
mascotasData.push({
id: doc.id,
...doc.data(),
});
});
res.status(200).json(mascotasData);
} catch (error) {
console.error('Error in getMascotasByOwner:', error);
res.status(500).json({ error: 'Internal server error.' });
}
});
在您的屏幕截图中,我们可以看到
ownerId
字段的值为 /users/1
,因此使用值为 .where('owner', '==', ownerId)
的 1
进行查询无法工作。
问题的解决方案取决于 owner
字段的
Firestore 数据类型。
ownerId
需要具有字符串值 /users/1
ownerId
需要定义为文档参考,如下:
const ownerId = admin.firestore()
.collection('users')
.doc('1');
const mascotasCollection = await admin.firestore().collection('pets').where('owner', '==', ownerId).get();