mergeOne method
Merges new data with an existing document by its ID.
This method performs a partial update by merging the provided data with the existing document. Only the specified fields are validated and updated, while other fields remain unchanged. Triggers CollectionEvent.onUpdate if successful.
Parameters:
id
- The string representation of the document's ObjectIddata
- The partial data to merge with the existing document
Returns:
- FormResultFree containing the merged document if successful
null
if the document doesn't exist
Example:
var result = await collection.mergeOne('507f1f77bcf86cd799439011', {
'email': 'newemail@example.com', // Only update email
'lastLogin': DateTime.now(), // Add new field
});
if (result?.success == true) {
print('Document merged successfully');
}
Implementation
Future<FormResultFree?> mergeOne(
String id,
Map<String, Object?> data,
) async {
var oldData = await getById(id);
if (oldData == null) {
return null;
}
FormResultFree validationResult = await validate(
data,
onlyCheckKeys: data.keys.toList(),
);
var newData = validationResult.formValues();
var mergedData = {
...oldData,
...newData,
};
if (validationResult.success) {
var result = await collection.replaceOne(
where.id(id.oID!),
mergedData,
upsert: false,
);
var newUpdate = await getById(id);
if (result.isSuccess && newUpdate != null) {
validationResult.updateValues(newUpdate);
await collectionEvent.onUpdate.emit(newUpdate);
}
return validationResult;
} else {
return await validate(mergedData);
}
}