Introduction
In this article, we will create a product model in MVC using Mongo DB. Please check the previous articles on MongoDB by visiting the following link:
Let's create a MVC application and add the products model.
The BSON specifiction doesn't have a type to directly represent a .Net decimal value. By default the driver represents it as a string. So let's change the representation to double after creating a test.
Create a folder named Products inside our MongoTests Project and add a class named ProductTests and create a test as shown:
namespace MongoTests.Products
{
using MongoDB.Bson;
using NUnit.Framework;
using ProductStore.Products;
[TestFixture]
public class ProductTests : AssertionHelper
{
[Test]
public void ToDocument_ProductwithPrice_PricerepresentedasDouble()
{
var product=new Product {Price = 1};
var document = product.ToBsonDocument();
Expect(document["Price"].BsonType, Is.EqualTo(BsonType.Double));
}
}
}
To test here we have inherited it from the Assertion helper and created a variable named document and set the result to BsonDocument on our product and an assertion for our resulting document.
Let's run the test and check.
As expected the test fails. To get this to pass we must decorate our Price property with the BSON Representation attribute and specify the BSON type for double, as shown.
[BsonRepresentation(BsonType.Double)]
public decimal Price { get; set; }
Now we need an Id ObjectIds; that is how documents in Mongo are typically identified. Let's add a string property named Id and test it.
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace ProductStore.Products
{
public class Product
{
public string Id { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public List<string> Location = new List<string>();
[BsonRepresentation(BsonType.Double)]
public decimal Price { get; set; }
}
}
And now create a new test in our Tests Project as in the following:
[Test]
public void ToDocument_ProductwithAnId_IdisrepresentedAsAnObjectId()
{
var product = new Product();
product.Id = ObjectId.GenerateNewId().ToString();
var document = product.ToBsonDocument();
Expect(document["_id"].BsonType,Is.EqualTo(BsonType.ObjectId));
}
It fails since it is a string, not an id.
To make this Test pass let's decorate the id field with a BSON representation attribute as in the following:
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
Summary
In this article, we learned how to work with a model in MVC using Mongo DB. In future articles, we will see some more features to complete the application.