Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hokaccha
Created April 4, 2014 03:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hokaccha/9967742 to your computer and use it in GitHub Desktop.
Save hokaccha/9967742 to your computer and use it in GitHub Desktop.

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);
  }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment