I would like ASP.NET MVC to return the document stored in MongoDB as JSON, but it does not need to serialize it to .NET first. However, BSONDocument.ToJSON () returns a JSON that looks like this:
{_id:ObjectId("someid")}
The browser JSON parser does not like "ObjectId (nnn)", and therefore the call fails with a parser error. I can get JSON with parsing using the Regex handle:
public ActionResult GetFormDefinitionsJSON() { var client = new MongoDB.Driver.MongoClient(ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString); var db = client.GetServer().GetDatabase("formthing"); var result = db.GetCollection("formdefinitions").FindAll().ToArray(); var sb = new StringBuilder(); sb.Append("["); var regex = new Regex(@"(ObjectId\()(.*)(\))"); var all = result.Select(x => regex.Replace(x.ToJson(), "$2")); sb.Append(string.Join(",", all)); sb.Append("]"); return Content(sb.ToString(), "application/json"); }
This returns JSON parsing:
{_id:"someid"}
But it smells. Is there a way, without using regular expression and string building hacking, to force the official MongoDB driver to return JSON that can be parsed by the browser? Alternatively, did I skip something on the browser side to allow {_id: ObjectId ("someid")} to be considered valid?
source share