Skip to content

Commit e46f139

Browse files
committed
Add fetchID()
1 parent a2047b8 commit e46f139

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

Sources/MongoDBModel/MongoDatabase.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ public struct MongoModelStorage: ModelStorage {
5757
try await database.delete(entity, for: id, options: options)
5858
}
5959

60+
public func fetchID(_ fetchRequest: FetchRequest) async throws -> [ObjectID] {
61+
let options = options.collections[fetchRequest.entity]
62+
return try await database.fetchIDs(fetchRequest, options: options)
63+
}
64+
6065
private func model(for entityName: EntityName) throws -> EntityDescription {
6166
guard let entity = self.model.entities.first(where: { $0.id == entityName }) else {
6267
throw CoreModelError.invalidEntity(entityName)
@@ -183,6 +188,31 @@ internal extension MongoDatabase {
183188
return results
184189
}
185190

191+
func fetchIDs(
192+
_ fetchRequest: FetchRequest,
193+
options: MongoCollectionOptions?
194+
) async throws -> [ObjectID] {
195+
let idKey = BSONDocument.BuiltInProperty.id.rawValue
196+
let entityName = fetchRequest.entity
197+
let collection = self.collection(entityName, options: options)
198+
let filter = fetchRequest.predicate.flatMap { BSONDocument(predicate: $0) } ?? [:]
199+
var options = FindOptions(fetchRequest: fetchRequest)
200+
options.projection = [
201+
idKey: .int32(1)
202+
]
203+
let stream = try await collection.find(filter, options: options)
204+
var results = [ObjectID]()
205+
for try await document in stream {
206+
guard let id = document[idKey]?.stringValue else {
207+
assertionFailure()
208+
throw CocoaError(.coderReadCorrupt)
209+
}
210+
assert(document.values.count == 1)
211+
results.append(ObjectID(rawValue: id))
212+
}
213+
return results
214+
}
215+
186216
func create(
187217
_ entityName: EntityName,
188218
for id: ObjectID,

0 commit comments

Comments
 (0)