updateField method
Updates a specific field of a document by its ID.
This method validates the new field value using the form definition before updating the document. Only the specified field is validated and updated. Triggers CollectionEvent.onUpdate if successful.
Parameters:
id
- String representation of the document's ObjectIdfield
- Name of the field to updatevalue
- New value for the field
Returns:
- FormResultFree containing the updated document if successful
null
if the document ID is invalid, doesn't exist, or the field is not defined in the form
Example:
var result = await collection.updateField(
'507f1f77bcf86cd799439011',
'status',
'inactive'
);
if (result?.success == true) {
print('Field updated successfully');
}
Implementation
Future<FormResultFree?> updateField(
String id,
String field,
Object? value,
) async {
var oid = ObjectId.tryParse(id);
if (oid == null || !await existId(id)) {
return null;
}
var fieldModel = form.fields[field];
if (fieldModel == null) {
return null;
}
DBFormFree newForm = DBFormFree(fields: {field: fieldModel});
FormResultFree formResult = await newForm.validate({field: value});
if (formResult.success) {
await collection.updateOne(where.id(oid), modify.set(field, value));
var newData = await getById(id);
if (newData != null) {
await collectionEvent.onUpdate.emit(newData);
return toFormResult(newData);
}
}
return formResult;
}