insert method
Inserts a new document into the collection.
This method validates the data before insertion and triggers the CollectionEvent.onInsert event if the insertion is successful.
Parameters:
data
- The document data to insert as a map of field names to values
Returns a FormResultFree containing:
- Validation results
- The inserted document with generated ID (if successful)
- Error information (if validation or insertion fails)
Example:
var result = await collection.insert({
'name': 'Jane Doe',
'email': 'jane@example.com',
'age': 30,
});
if (result.success) {
print('Inserted with ID: ${result.formValues()['_id']}');
}
Implementation
Future<FormResultFree> insert(Map<String, Object?> data) async {
var validationResult = await validate(data);
if (validationResult.success) {
var result = await collection.insertOne(validationResult.formValues());
if (!result.isFailure && result.document != null) {
validationResult.updateValues(result.document!);
await collectionEvent.onInsert.emit(result.document);
} else {
validationResult.updateFromMongoResponse(result.serverResponses);
}
}
return validationResult;
}