Embedded Documentsの場合はDocumentに配列とかでも持つから同期的に子要素を取得できる。
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// commentsをEmbedded Documentsにするパターン
var Blog = new Schema({
title: String,
body: String,
comments: [{
name: String,
body: String
}]
});
Blog.method({
// comments idからcommentを一件返す
findCommentById: function(id) {
// 自分のカラムにcommentsを配列でもってるから同期で取得できる
return this.comments.id(id);
}
});
正規化して別Collectionにわけちゃうとクエリ発行しないといけないので非同期になっちゃう(リレーションのところは擬似コードなのでこのままだと動きません)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// commentsを正規化して別Collectionに分けるパターン
var Blog = new Schema({
title: String,
body: String
});
var Comment = new Schema({
name: String,
body: String
});
Blog.method({
// comments idからcommentを一件返す
findCommentById: function(id, fn) {
// クエリ発行しないといけないから非同期になっちゃう
this.comments.findById(id, fn);
}
});