Node.js how to pass geojson from mongodb to object I can use in frontend

34 views
Skip to first unread message

Artur Tochowicz

unread,
Jun 17, 2016, 6:50:27 PM6/17/16
to nodejs

I am trying to cluster 5m points stored in mongoDB. Maximum result from 1 query is currently just around 1m so I have decided to use: PruneCluster for first visuals. Points are stored as geoJSON object and there is an 2dsphere index on them.

I connect to mongodb using native node.js driver and query to find points within a polygon, that will only return loc field from the collection and route result for preview:

router.get('/map', function(resq,res) {
  var MongoClient = mongodb.MongoClient;
  var url = 'mongodb://localhost:27017/airboost';

  MongoClient.connect(url, function(err, db) {
    if(err){
      console.log('Unable to connect to db ', err);
    } else {
        console.log('Connected!!!');

        var collection = db.collection('listingsF');

        collection.find({
           loc: {
             $geoWithin: {
                $geometry: {
                   type : "Polygon" ,
                       coordinates: [[[121.48521363894814,31.41360430073249],[...],[121.48865692654915,31.41168940543709]]]
                            }
                          }
                }
          },{loc:1}).toArray(function(err, result){

          if (err) {
            res.send(err);
          } else if (result.length) {
            res.send(result);
          } else {
            res.send('Nothing found');
          }
          db.close();
        });
      }
  });
});

I get a list of objects like this:

[
  {
    "_id": "567f972bad55ac0797baa75b",
    "loc": {
      "type": "Point",
      "coordinates": [
        -85.84556526181,
        10.29620625503
      ]
    }
  },
  {
    "_id": "567f972bad55ac0797baa75c",
    "loc": {
      "type": "Point",
      "coordinates": [
        -54.943878777465,
        -34.964002797642
      ]
    }
  }
]

Then I need to pass that result somehow to function in script from /public folder, So I can display the cluster on leaflet map:

var pruneCluster = new PruneClusterForLeaflet();
  ... 
var marker = new PruneCluster.Marker(latitude, longitude);
pruneCluster.RegisterMarker(marker);
  ... 
leafletMap.addLayer(pruneCluster);

I can print content with jade anyway I want, but have no idea how to pass all that mongodb data as Markers to PruneCluster. I don't need full code just a point to a direction. Can someone help me?

Reply all
Reply to author
Forward
0 new messages