replaceOne method

Future<FormResultFree?> replaceOne(
  1. String id,
  2. Map<String, Object?> data
)

Replaces an entire document by its ID.

This method completely replaces the existing document with new data, after validating the new data. The document must exist for the operation to succeed. Triggers CollectionEvent.onUpdate if successful.

Parameters:

  • id - The string representation of the document's ObjectId
  • data - The new document data to replace the existing document

Returns:

  • FormResultFree containing the updated document if successful
  • null if the document ID is invalid or doesn't exist

Example:

var result = await collection.replaceOne('507f1f77bcf86cd799439011', {
  'name': 'John Smith',
  'email': 'john.smith@example.com',
  'age': 35,
});

if (result?.success == true) {
  print('Document replaced successfully');
}

Implementation

Future<FormResultFree?> replaceOne(
  String id,
  Map<String, Object?> data,
) async {
  var oid = ObjectId.tryParse(id);
  if (oid == null || !await existId(id)) {
    return null;
  }

  FormResultFree validationResult = await validate(data);
  if (validationResult.success) {
    var newData = validationResult.formValues();
    newData['_id'] = oid;
    var result = await collection.replaceOne(
      where.id(oid),
      newData,
    );
    var newUpdate = await getById(id);
    if (result.isSuccess && newUpdate != null) {
      validationResult.updateValues(newUpdate);
      await collectionEvent.onUpdate.emit(newUpdate);
    }
  }

  return validationResult;
}