我需要避免在集合中创建重复项。
我的情况: 如果 collection_1 已经包含属性值,我需要在 collection_2 文档中引用该文档,否则需要在 collection_1 中创建文档,然后创建< strong> collection_2 文档及其参考,我已经尝试过
processData(List<Song> _songs) async {
_songs.asMap().forEach((_index, _song) async {
final result = await checkMusicDirAvailability(_song, _index);
if (mdAvailable) {
//add song
print((_index + 1).toString() + ' already available');
DocumentReference songRef = await addSongDetails(_song, mdRef);
print(songRef.documentID);
} else {
//add musicdir then song
print((_index + 1).toString() + ' not available');
DocumentReference mdDocRef = await createMusicDirectorDoc(_song.music);
DocumentReference songRef = await addSongDetails(_song, mdDocRef);
print(songRef.documentID);
}
});
}
Future<DocumentReference> checkMusicDirAvailability(
Song songDetails,
int _index,
) async {
DocumentReference refmusicDiret = await databaseReference
.collection("music_directors")
.where('m_d_name', isEqualTo: songDetails.music)
.limit(1)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length != 0) {
setState(() {
mdAvailable = true;
mdRef = snapshot.documents[0].reference;
});
} else {
setState(() {
mdAvailable = false;
});
}
});
return refmusicDiret;
}
但是它总是在第一次执行时创建重复项,我认为创建文档的延迟可能会导致这种情况。我刚刚在工作中错过的一切。