title: Understanding Relationships & Foreign Keys in Mongoose
body: <p>In MongoDB/Mongoose, how do I define a relationship? I think there are a few ways I've seen, but I'm not sure I understand the differences or when do I use which. I am using Mongoose 3</p>
  <p>I've defined <code>Todo</code> and <code>TodoList</code> model, where the relationship is obvious. So following the docs <a href="http://mongoosejs.com/docs/documents.html" rel="nofollow noreferrer">http://mongoosejs.com/docs/documents.html</a>, I've defined classes like:</p>
  <pre><code># Todo.coffee
  mongoose = require &quot;mongoose&quot;
  
  todoSchema = mongoose.Schema
      name: String
      desc: String
      dueOn: Date
      completedOn: Date
  
  module.exports = mongoose.model &quot;Todo&quot;, todoSchema
  
  # TodoList.coffee
  
  mongoose = require &quot;mongoose&quot;
  Todo = require &quot;./Todo&quot;
  
  todoListSchema = mongoose.Schema
      name: String
      todos: [Todo.schema]
  
  module.exports = mongoose.model &quot;TodoList&quot;, todoListSchema
  </code></pre>
  <p>Then I tried testing the classes:</p>
  <pre><code>list = new TodoList
      name: &quot;List 1&quot;
      todos: [
          { name: &quot;Todo 1&quot;, desc: &quot;Hello&quot;, dueOn: new Date(2012,10,1), completedOn: new Date(2012,10,2) }
          { name: &quot;Todo 2&quot; }
          { name: &quot;Todo 3&quot;, desc: &quot;Hello 2&quot;, dueOn: new Date(2012,10,6), completedOn: new Date(2012,10,2) }
          { name: &quot;Todo 4&quot; }
      ]
  #list.todos.push { name: &quot;Todo 5&quot; }
  console.log &quot;List&quot;, list
  list.save (err) -&gt;
      if !err
          TodoList.find {}, (err, lists) -&gt;
              console.log &quot;TODOS&quot;
              console.log lists.length, lists
              done(err)
      else 
          console.log &quot;ERROR!!!&quot;
          done err
  </code></pre>
  <p>When I try to do <code>Todo.find()</code> I get nothing, so the Model (<code>Todo.coffee</code>) is kind of redundant? It looks like <code>Todo</code> are stored in <code>TodoList</code>, as a user I may not care, but I wonder what are the implications? Eg. will the document get too large? 1 TodoList with too many Todos? Does that matter? What if I allow nested Todos (not that I want to do itm just for understanding), is it better to store documents separately then? How do I do that, if I so desire, and when do I do it?</p>
  <p>I saw another method, in Mongoose 2 actually. I don't know, if it is possible in 3. Something like using <code>ObjectId</code> instead of nested docs. Maybe thats to store it separately?</p>