Node.js如何将geojson从mongodb传递给我可以在前端使用的对象

我正在尝试将存储在mongoDB中的5m点进行聚类。 1查询的最大结果目前只有1米左右,所以我决定使用: PruneCluster作为第一个视觉效果。 点存储为geoJSON对象,并在其上有2dsphere索引。

我使用本机node.js驱动程序连接到mongodb并查询以find多边形内的点,这将只会从集合和路由结果中返回loc字段以进行预览:

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(); }); } }); }); 

我得到这样的对象列表:

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

然后,我需要通过/公用文件夹脚本从某种程度上传递该结果,所以我可以在小册子地图上显示集群:

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

我可以用任何方式打印内容,但是我不知道如何将所有的mongodb数据作为标记传递给PruneCluster。 我不需要完整的代码只是指向一个方向。 有人能帮我吗?

你可以很容易地在你的传递对象的翡翠中创build一个variables:

 // server.js res.render('something', { something: mogoDBObject }); // Your template.jade script. var myGeoJSONArray = !{something}; // If you're getting problems parsing the array of objects // ie "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.reverse()); marker.push(marker); ... });