set method
Implementation
DocRefMemory set(
Map<String, dynamic> newDoc,
) {
String collId = _collRef.id;
// create the doc parent collection if not exist
if (_memoryDb[collId] == null) {
_memoryDb[collId] = [];
}
// get the old data if not exist create one
int index =
_memoryDb[collId]!.indexWhere((element) => element[DBRKeys.id] == _id);
// insert new one if the old one doesn't exist
if (index == -1) {
newDoc[DBRKeys.id] = newDoc[DBRKeys.id] ?? _id;
return _collRef.insertDoc(newDoc);
}
// or just remove the old one and set the new one
// the id of a doc can't be changed
var oldDoc = _memoryDb[collId]![index];
String docId = oldDoc[DBRKeys.id];
newDoc[DBRKeys.id] = docId;
// get the old doc index in the collection
_memoryDb[collId]![index] = newDoc;
var newDocRef = DocRefMemory(_id, _collRef, _memoryDb);
return newDocRef;
}