MongoDB best practice for referencing

Xatep picture Xatep · Feb 14, 2013 · Viewed 12.2k times · Source

I'm wondering what the best practice for modelling by using references would be given situation under. I'm using MongoRepository library.

public class User : Entity
{
   publis string Id { get; set; }
   public string Email { get; set; }
   public string Password { get; set; }
}

public class Post : Entity
{
   public string Id { get; set; }
   public string Title { get; set; }
   public string Summary { get; set; }
   public DateTime Added { get; set; }
   public User Owner { get; set; }
}

When storing the Post I want only reference to Owner (User) object instead of whole object underlying.

Currently I'm doing it like this, not knowing of better way...

var post = new Post
{
   Title = "Example title",
   Summary = "asd asd",
   Added = DateTime.Now,
   Owner = new User { Id = "someExistingUserId" }
};
postRepository.Update(post); //Save

..

//Then to get the post
var post = postRepository.GetById("previouslySavedPostId");
post.Owner = userRepository.GetById(post.Owner.Id);
return post;

userRepository and postRepository are of MongoRepository type.

Is this the correct approach to solving my problem using MongoDB with C#/MVC(4)?

Answer

Jasmin Gacic picture Jasmin Gacic · Mar 6, 2013

You can use MongoDBRef object instead of User object.

public class Post : Entity
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Summary { get; set; }
    public DateTime Added { get; set; }
    public MongoDBRef Owner { get; set; }
}    

Then you can:

var mongo = new Mongo(config.BuildConfiguration());
mongo.Connect();        
var DB = mongo.GetDatabase(_dataBaseName)

var post = new Post();
post.Owner = new MongoDBRef("User", userId); // First parameter is a mongoDB collection name and second is object id
// To fetch object referenced by DBRef you should do following
var owner = DB.FollowReference<User>(post.Owner);