mongooseでリレーション

embededじゃなくて正規化してリレーションしたい場合。これでいいのかわからんけど。mongoose.Schema.ObjectIdというのがSchemaの指定に使えるっぽいので

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  , ObjectId = Schema.ObjectId;

var BlogSchema = new Schema({
  title: String,
  body: String,
  created_at: Date
});

var CommentSchema = new Schema({
  body: String,
  blog: ObjectId
});

var Blog = mongoose.model('Blog', BlogSchema);
var Comment = mongoose.model('Comment', CommentSchema);

こんな感じにして

Blog.create({
  title: 'title',
  body: 'blog',
  created_at: Date.now()
}, function(err, blog) {
  Comment.create({
    blog: blog.id,
    body: 'comment'
  }, function(err, comment) {
    console.log(err);
  });
});

// > db.blogs.find()
// { "_id" : ObjectId("4e3bd2079969190ce8000001"), "created_at" : ISODate("2011-08-05T11:20:39.062Z"), "body" : "blog", "title" : "title" }
// > db.comments.find()
// { "_id" : ObjectId("4e3bd2079969190ce8000002"), "body" : "comment", "blog" : ObjectId("4e3bd2079969190ce8000001") }

こういうデータ入れる。


親から子を引く場合。

Blog.findOne({ title: 'title' }, function(err, blog) {
  Comment.find({ blog: blog.id }, function(err, comments) {
    console.log(comments);
  });
});

// [ { blog: 4e3bd2079969190ce8000001,
//   body: 'comment',
//   _id: 4e3bd2079969190ce8000002 } ]

子から親を引く。

Comment.findById('4e3bd2079969190ce8000002', function(err, comment) {
  Blog.findById(comment.blog, function(err, blog) {
    console.log(blog);
  });
});

//{ title: 'title',
//  body: 'blog',
//  created_at: Fri, 05 Aug 2011 11:20:39 GMT,
//  _id: 4e3bd2079969190ce8000001 }

Comment.findByBlogIdとかblog.getComments()とか定義しとけばそんな面倒じゃないかな。