toHo toHo - 5 months ago 31
Node.js Question

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

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 any way I want, but I 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?

Answer

You can easily create a variable in jade of your passed object:

// server.js
res.render('something', {
  something: mogoDBObject
});

// Your template.jade
script.
  var myGeoJSONArray = !{something};
  // If you're getting problems parsing the array of objects
  // i.e. "something" becomes something like [[object Object], ...]
  // use myGeoJSONArray = JSON.parse('!{JSON.stringify(something)}');
script(src='path/to/public/folder/main.js')

// path/to/public/folder/main.js
/* Do Something with your variable myGeoJSON */
myGeoJSONArray.forEach(geoJSON=>{
  var marker = new PruneCluster.Marker(...geoJSON.loc.coordinates);
  marker.push(marker);
  ...
});