Skip to content

Instantly share code, notes, and snippets.

@ilantoren
Created July 21, 2021 07:00
Show Gist options
  • Save ilantoren/7e1564a1b3ba1882bc4f3b164bcbe33b to your computer and use it in GitHub Desktop.
Save ilantoren/7e1564a1b3ba1882bc4f3b164bcbe33b to your computer and use it in GitHub Desktop.
Code for a Realm function to find restaurants within a given neighborhood and to extract the data for further code steps
/*
* restaurantsByNeighborhood
* @param string neighborhood
* @returns object
*/
exports = function(neighborhood){
// A simple function to create an average coordinate
// for centering the map.
const avg = function( arr ) {
let k = 0;
let l = 1
for( let j of arr) {
k=k+j
l=l+1
}
return k/l
}
// result is what is passed back
let result = {}
// aggregation pipeline for the neighborhood collection
// this was taken from the Compass export to code menu for javascript
let pipeline = [{$match: {
name: neighborhood
}}, {$project: {
name:1,
coord: {$arrayElemAt:["$geometry.coordinates", 0]},
_id: 0
}}, {$addFields: {
long: {$map: {input: "$coord", in: {$arrayElemAt: ["$$this", 0]}}},
lat: {$map: {input: "$coord", in: {$arrayElemAt: ["$$this", 1]}}}
}}];
// atlas specific - getting a db connection to the two collections: neighborhoods and restaurants
let collection = context.services.get("mongodb-atlas").db("sample_restaurants").collection("neighborhoods");
let restaurants = context.services.get("mongodb-atlas").db("sample_restaurants").collection("restaurants");
collection.aggregate( pipeline ).next().then( a => {
result.coord = a.coord;
let long = a.long;
avg_long = avg( long )
let lat = a.lat
avg_lat = avg( lat )
result.name = a.name
let resultList = restaurants.find( {"address.coord" : {$geoWithin: { $geometry: {type: "Polygon", coordinates: [a.coord] }}}}).toArray()
result.restaurants = resultList;
result.long = long
result.lat = lat
});
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment