MongoDB best practice for referencing MongoDB best practice for referencing mongodb mongodb

MongoDB best practice for referencing


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 followingvar owner = DB.FollowReference<User>(post.Owner);


Mongo is a document database and if you are used to using sql server it requires a slightly different way of thinking.

As you don't want the user password details in every single post, the way i would probably do it is to create a new class to contain any user info that might be required to display a post.

public class PostOwnerInfo{    public string UserId { get; set; }    public string Name { get; set; }}

Update your post entity, replacing the Owner property with an OwnerInfo property, of type PostOwnerInfo.

Then when you create a new post, do the following.

var user = userRepository.GetById(someExistingUserId);var post = new Post{   Title = "Example title",   Summary = "Example summary",   Added = DateTime.Now,   OwnerInfo = new PostOwnerInfo   {        UserId = user.Id,        Name = user.Name   }};postRepository.Update(post);

This way when you query for a post it will have all the user info that you require to display the post in it's OwnerInfo property with no further queries required.

var post = postRepository.GetById(previouslySavedPostId);// post.OwnerInfo will contain user info

There is a certain amount of data redundancy, but in an document database this is how i would do it.

If you need the full user info for any reason just do a seperate query for it as you were doing before.

The idea is that you store all the user info you need for a post in a child document of the post, so you shouldn't need to do a seperate query for the user.

If the user data chages, just update the UserInfo field on all posts made by your user.

Your user data will rarely change, but you will query for posts very often.