Okay, so I’m working with Couchbase 2.0 and the most recent .NET client.
Basically what I’m writing is a project to keep track of goals (a glorified to-do list)…
I’ve managed to store a goal object as a JSON document within couchbase and then deserialize it back into a POCO, but my question is how to automatically lookup the linked documents and populate the subGoal List<Goal>
Not sure if this kind of automatic deserialization is possible without some logic to handle it within the code itself but any pointers appreciated, cheers!
JSON
{
id: "goal_1",
name: "goal 1",
description: "think of some better projects",
subGoals: [goal_2, goal_3]
}
C#
var goal = client.GetJson<Goal>(id);
return goal;
Here’s the POCO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace stuff.Models
{
public class Goal
{
protected DateTime _targetDate;
/// <summary>
/// Name of the goal
/// </summary>
[JsonProperty("name")]
public String Name { get; set; }
/// <summary>
/// Full description of the goal
/// </summary>
[JsonProperty("description")]
public String Description { get; set; }
/// <summary>
/// Target date for completing this goal
/// </summary>
[JsonProperty("targetDate")]
public DateTime? TargetDate
{
get
{
return _targetDate;
}
set
{
// target date must be later than any sub-goal target dates
}
}
/// <summary>
/// Any sub-goals
/// </summary>
[JsonProperty("subGoals")]
public List<Goal> SubGoals { get; set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="Name"></param>
/// <param name="Description"></param>
/// <param name="TargetDate"></param>
/// <param name="SubGoals"></param>
public Goal(String Name, String Description, DateTime? TargetDate = null, List<Goal> SubGoals = null)
{
this.Name = Name;
this.Description = Description;
this.TargetDate = TargetDate;
this.SubGoals = SubGoals;
}
}
}
There’s no automatic way to get related documents back in one “join” query, however you could use a collated view. So given a set of goals like below (note the addition of a type property):
You would then write a view that outputs each parent goal followed by its children:
The output of this view is a set of rows, where each row contains a key consisting of the parent ID and a 0, followed by its children and a 1 (the 0 and 1 ensure that the rows are ordered correctly):
In the .NET SDK tutorial, I describe how to query a collated view (a Brewery and its beers).
http://www.couchbase.com/docs/couchbase-sdk-net-1.2/collatedviews.html