Working with GUIDs in MongoDB and ASP.NET MVC3

Just a small tip for those looking to use GUIDs as document IDs in MongoDB in conjunction with ASP.NET MVC3: it’s a lot more straightforward than it may seem at the onset.

These examples are based off of the ASP.NET MVC3 tutorials…except with MongoDB instead of EF+SQL Server.

I’ve set up my model class like so:

When the application creates an object and persists it to the database, you’ll see that it shows up like this in the Mongo console (I’ve formatted the JSON for clarity):

If you try to serialize this to JSON, instead of getting a GUID string, you’ll get:

This is somewhat inconvenient if you want to work with it from a pure JavaScript perspective; I was hoping that it would have returned a GUID as a string instead.  I was also concerned that this meant that I’d have to manage this manually as well on the server side in my actions, but it turns out that it works better than expected.  The only caveat is that you have to use “_id” when creating queries; otherwise, you can use the GUID as-is and the Mongo APIs will convert it behind the scenes:

You can see the result below in the browser:

Note the properly formatted GUID in the URL

So far, so good with my little Mongo+MVC3 experiment 😀

You may also like...