updateField method

Future<FormResultFree?> updateField(
  1. String id,
  2. String field,
  3. Object? value
)

Updates a specific field of a document by its ID.

The id should be a valid MongoDB ObjectId string. The field specifies the field to be updated, and value is the new value to be assigned.

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 = 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) {
      return toFormResult(newData);
    }
  }

  return formResult;
}