copy method

Future<void> copy(
  1. String id
)

Creates a copy of a document by its ID and inserts it as a new document.

This method retrieves an existing document, removes its _id field, and inserts it as a new document with a newly generated ObjectId. Triggers CollectionEvent.onInsert if the copy operation is successful.

Parameters:

  • id - String representation of the source document's ObjectId

The method silently fails if the ID is invalid or the document doesn't exist.

Example:

await collection.copy('507f1f77bcf86cd799439011');
// Creates a new document with the same data but different _id

Implementation

Future<void> copy(String id) async {
  var oid = ObjectId.tryParse(id);
  if (oid != null) {
    var data = await collection.findOne(where.id(oid));
    if (data != null) {
      data.remove('_id');
      var result = await collection.insertOne(data);
      if (result.isSuccess) {
        await collectionEvent.onInsert.emit(result.document);
      }
    }
  }
}