当我尝试以 450 的间隔批量插入记录时(我选择此选项是为了确保低于 500 个 Firestore 限制),我收到无效参数的错误。下面是我正在使用的确切代码。
我在react-native中使用firestore,具有以下依赖项和版本:
"@react-native-firebase/app": "^19.1.0",
"@react-native-firebase/firestore": "^19.1.0",
"react-native": "^0.73.5",
我正在将记录插入尚不存在的子集合中。
user_tracks
是存在的顶级集合,文档ID是记录指示符,仅用于链接顶级集合和子集合。文档 id 对应于 users 集合下的现有文档 id,最后子集合 tracks
是我最终尝试插入的内容。
export const updateUserLikedSongs = async (documentId, likedSongs) => {
// Batch write 500 at a time
console.log(`There are ${likedSongs.length} songs to insert.`);
if (likedSongs.length <= 0) {
console.log("No more documents to insert.");
return true;
}
const batchSize = 450; // Firestore batch size limit
var batch = firestore().batch();
likedSongs.slice(0, batchSize).forEach((song) => {
const docRef = firestore().collection("user_tracks").doc(documentId).collection("tracks").doc();
batch.set(docRef, song); // Use song directly, no need for Object.assign
});
try {
await batch.commit();
console.log(`Successfully wrote ${batchSize} records.`);
// Recursively call updateUserLikedSongs with the remaining songs
return updateUserLikedSongs(documentId, likedSongs.slice(batchSize));
} catch (error) {
console.error("Error while batch writing:", error);
throw error; // Rethrow the error to be caught by the caller
}
};
我可以循环遍历我喜欢的歌曲数组并将它们一次插入到子集合 1 中,但这似乎效率极低,我需要一些帮助来找出我在批量插入时做错了什么。由于等待解决的承诺数量较多,此方法还会引发警告。
export const updateUserLikedSongs = async (documentId, likedSongs) => {
likedSongs = likedSongs.slice(0, 750)
// Batch write 500 at a time
console.log(`There are ${likedSongs.length} songs to insert.`);
const batchSize = 499; // Firestore batch size limit
const batches = [];
for (let i = 0; i < likedSongs.length; i += batchSize) {
const batch = likedSongs.slice(i, i + batchSize);
const batchPromises = batch.map(async (track) => {
const docRef = firestore()
.collection(`user_tracks/${documentId}/tracks`)
.doc();
await docRef.set(track); // Set each record in Firestore
});
batches.push(Promise.all(batchPromises));
}
try {
// Wait for all batches to complete
await Promise.all(batches);
console.log("All records created successfully.");
} catch (error) {
console.error("Error creating records:", error);
}
};
我已经通过react-native在android和ios上尝试过这个,但我认为这并不重要,因为javascript代码和依赖项最终是相同的。
请提供一些提示和指导。
事实证明我需要逐行查看每一段代码。
第二组有效的代码,我通过指定整个集合路径
/user_tracks/${documentId}/tracks
来创建新的文档记录,与第一组代码一样,我使用firestore().collection("user_tracks").doc(documentId).collection("tracks").doc()
构建它。
这最终导致了错误,这对我来说很有趣,因为我相信我读到这是引用子集合的有效方式。