Skip to content

Instantly share code, notes, and snippets.

@saroar
Created November 24, 2020 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saroar/6677eb8906fa4bc888c455b0dde87441 to your computer and use it in GitHub Desktop.
Save saroar/6677eb8906fa4bc888c455b0dde87441 to your computer and use it in GitHub Desktop.
You can use Fluent with MongodbKitten and get fluent like paginate
private func readAll(_ req: Request) throws -> EventLoopFuture<EventPage> {
if req.loggedIn == false {
throw Abort(.unauthorized)
}
//{ coordinates: {$geoWithin: { $centerSphere: [ [ 30.205643177032474, 60.02979119847114 ], 0.008226198370569168 ]}}, $or: [] }
//db.event_places.find({"coordinates" : { $geoWithin : { $centerSphere : [[30.387906785397426, 60.01087797211564], 0.008226198370569168 ]}}}).limit(3) //.pretty()
// .aggregate([.geoNear(longitude: 30.387906785397426, latitude: 60.01087797211564, distanceField: "0.008226198370569168", spherical: false)])
//.skip(NUMBER_OF_ITEMS * (PAGE_NUMBER - 1)).limit(NUMBER_OF_ITEMS )
let coordinates: Document = [ [30.387906785397426, 60.01087797211564], 0.008226198370569168]
let query: Document = [
"coordinates": [
"$geoWithin": [
"$centerSphere": coordinates
]
]
]
let db = req.mongoDB
let events = db[Event.schema]
let page = try req.query.decode(PageRequest.self)
let numberOfItems =
events
.aggregate([.
geoNear(
longitude: 30.387906785397426,
latitude: 60.01087797211564,
distanceField: "0.008226198370569168",
spherical: false
),
.count(to: "name")]
).count()
return numberOfItems.flatMap { count -> EventLoopFuture<EventPage> in
let allResults = events
.find(query)
.skip(page.per * (page.page - 1))
.limit(page.per)
.decode(Event.Item.self)
.allResults()
return allResults.map { results in
let meta = PageMetadata(page: page.page, per: page.per, total: count)
let page = EventPage(items: results, metadata: meta)
return page
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment