Question

I'm attempting to use the mongodb c# driver to generate json from a collection of GIS objects stored in the GeoJson format. I then send this data to my page and use GeoJson.js to map the data using the Google Maps api. Here's a simplified, hacky version of my controller method:

public JavaScriptResult GetMapData( IEnumerable<OilGasLeaseModel> leases )
{
  var client = new MongoClient(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
  var server = client.GetServer();
  var db = server.GetDatabase("GIS");
  var collection = db.GetCollection<GeoJsonFeature<GeoJson2DGeographicCoordinates>>("Sections");

  HashSet<string> sections = new HashSet<string>();
  foreach (OilGasLeaseModel ogl in leases)
  {
    foreach (TractModel tract in ogl.Tracts)
    {
      sections.Add(String.Format("{0}-T{1}-R{2}", tract.sec.TrimStart('0'), tract.twn, tract.rng));
    }
  }

  //var query = Query<GeoJsonFeature<GeoJson2DGeographicCoordinates>>.Where(x => x.Properties["SECTION"].ToString() == "20-T15N-R05W" );
  var result = collection.FindAll().Where(x => sections.Contains( x.Properties["SECTION"].AsString  ) );
  return JavaScript(result.ToJson());
}

this code generates JSON that looks like:

[{ "type" : "Feature", "geometry" : { "type" : "Polygon", "coordinates" : [[[-97.602787016351414, 35.885755787882609], [-97.602844545557346, 35.881887460152967], [-97.6029024469591, 35.877283343404464], [-97.602876585570769, 35.871308155111066], [-97.616576075082719, 35.8711729277396], [-97.620908123078735, 35.871311565900726], [-97.620823160030156, 35.878294258522239], [-97.620823169953638, 35.881567848717381], [-97.620766650314266, 35.88571083185078], [-97.613535371346188, 35.88577902182432], [-97.611143428162308, 35.885803641463667], [-97.602787016351414, 35.885755787882609]]] }, "properties" : { "Shape_area" : 2615635.67494, "SECT_NUM" : "10", "SECTION" : "10-T16N-R4W", "EAST_WEST" : "W", "NORTH_SOUT" : "N", "Order_" : 0, "RANGE" : "4", "Shape_len" : 6453.04509751, "STR" : "10-16N-04W", "OBJECTID_1" : 2071, "TOWNSHIP" : "16", "MERIDIAN" : "IM" }, "_id" : ObjectId("52ddb2399f3a3124806d5a65") }, ... ]

the problem is that this is apparently not valid JSON, as I get an the error:

Uncaught ReferenceError: Objectid is not defined

When I try to use the resulting JSON as javascript.

Is there some way that I can get the ToJson extension method to just convert the _id to a string, instead of ObjectId("52ddb2399f3a3124806d5a65") ?

Any tips would be appreciated!

Was it helpful?

Solution

Ok, turns out that the Mongodb c# driver makes this very easy:

replace:

return JavaScript(result.ToJson());

with:

return JavaScript(result.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top