[英]Firestore cloud-function to update a field in all doc in coll with parameter
我有一個 firestore 集合“ Messages
”,帶有一個布爾字段“ viewed
”和一個字段“ userToRef
”,其中包含一個coll:Users
-reference。 我希望我的雲功能將coll:Message
中所有文檔中的字段“ viewed
”更新為“ True
”,這些文檔在字段“ userToRef
”中具有與 URL 參數“ userRef
”相同的用戶引用。
但無論我做什么,它都會引發404-error
:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.allMsgOfUserRead = functions.https.onRequest((req, res) => {
// Get the user reference from the request with the id of the document
const strRef = req.query.userRef;
const userRef = admin.firestore().collection('Users').doc(strRef);
// Update the "viewed" field of all documents in the "Messages" collection
// where the "userToRef" field matches the user reference
return admin.firestore()
.collection('Messages')
.where('userToRef', '==', userRef)
.get()
.then(snapshot => {
if (!snapshot.exists) {
// Document does not exist, return an error response
return res.status(404).json({
message: `Messages to User not found ${req.query.userRef}`,
code: 404
});
}
snapshot.forEach(doc => {
doc.ref.update({ viewed: true });
});
return res.json({
message: 'Success',
code: 200
});
})
.catch(error => {
return res.status(500).json({
message: 'Error occurred',
code: 500
});
});
});
我真的需要一個想法,為什么會這樣……謝謝!
我從未嘗試過編寫這樣的代碼,但我強烈懷疑當您使用admin.firestore().collection('Users').doc(strRef)
作為搜索代碼中的鍵時您會得到什么 .where .where('userToRef', '==', userRef)
。
也許您想使用req.query.userRef
代替?
return admin.firestore()
.collection('Messages')
.where('userToRef', '==', req.query.userRef)
.get()
...
您不應在forEach()
循環中執行一組對異步update()
方法的調用。 您應該使用Promise.all()
,如下所示。 另外,請注意QuerySnapshot
始終存在並且可能為空:使用empty
屬性進行檢查。
exports.allMsgOfUserRead = functions.https.onRequest((req, res) => {
// Get the user reference from the request with the id of the document
const strRef = req.query.userRef;
const userRef = admin.firestore().collection('Users').doc(strRef);
// Update the "viewed" field of all documents in the "Messages" collection
// where the "userToRef" field matches the user reference
admin.firestore() // <= No need to return here, since we don't return a Promise chain in an HTTPS Cloud Function
.collection('Messages')
.where('userToRef', '==', userRef)
.get()
.then(snapshot => {
if (snapshot.empty) {
// Document does not exist, return an error response
res.status(404).json({
message: `Messages to User not found ${req.query.userRef}`,
code: 404
});
} else {
const promises = [];
snapshot.forEach(doc => {
promises.push(doc.ref.update({ viewed: true }));
});
return Promise.all(promises)
}
})
.then(() => {
res.json({
message: 'Success',
code: 200
});
})
.catch(error => {
res.status(500).json({
message: 'Error occurred',
code: 500
});
});
});
由於您的代碼中有一個if
塊,我會使用async
/ await
關鍵字以獲得更簡單和更清晰的代碼:
exports.allMsgOfUserRead = functions.https.onRequest(async (req, res) => {
try {
// Get the user reference from the request with the id of the document
const strRef = req.query.userRef;
const userRef = admin.firestore().collection('Users').doc(strRef);
// Update the "viewed" field of all documents in the "Messages" collection
// where the "userToRef" field matches the user reference
const snapshot = await admin.firestore()
.collection('Messages')
.where('userToRef', '==', userRef)
.get();
if (snapshot.size === 0) {
// Document does not exist, return an error response
res.status(404).json({
message: `Messages to User not found ${req.query.userRef}`,
code: 404
});
} else {
const promises = [];
snapshot.forEach(doc => {
promises.push(doc.ref.update({ viewed: true }));
});
await Promise.all(promises);
res.json({
message: 'Success',
code: 200
});
}
} catch (error) {
res.status(500).json({
message: 'Error occurred',
code: 500
});
}
});
最后說明: QuerySnapshot
很可能包含 0 或 1 個QueryDocumentSnapshot
(只有一個用戶對應於特定的用戶引用,不是嗎?),因此您實際上不需要循環。 如果QuerySnapshot
不為空,您可以使用snapshot.docs[0]
獲取唯一文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.