Because this took me a long time to figure out I thought I'd share it with people in case other people get stuck on the same problem.
The problem is that Mongoose doesn't support DBRefs. A DBRef
is just a little sub structure with a two keys: $ref
and $id
where $id
is an ObjectId
instance. Here's what it might look like on the mongodb shell:
> db.questions.findOne();
{
"_id" : ObjectId("4d64322a6da68156b8000001"),
"author" : {
"$ref" : "users",
"$id" : ObjectId("4d584fb86da681668b000000")
},
"text" : "Foo?",
...
"answer" : "Bar"
"genre" : {
"$ref" : "question_genres",
"$id" : ObjectId("4d64322a6da68156b8000000")
}
}
DBRefs are very convenient because various wrappers on drivers can do automatic cross-fetching based on this. For example, with MongoKit I can do this:
for question in db.Question.find():
print question.author.first_name
If we didn't have DBRefs you'd have to do this:
for question in db.Question.find():
author = db.Authors.findOne({'_id': question.author})
print author.first_name