26
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mongooseでリレーション

Posted at

リレーションの指定

Schemaに{ type: ObjectId, ref: 'Story' }のように指定する

var mongoose = require('mongoose')
  , Schema = mongoose.Schema
  
var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

find時にリレーション先のドキュメントも一緒に取得する

populate('_creator')のように指定する。

Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
  if (err) return handleError(err);
  console.log('The creator is %s', story._creator.name);
  // prints "The creator is Aaron"
})

参考

Mongoose Query Population v3.8.21
http://mongoosejs.com/docs/populate.html

mongooseでリレーション - hokaccha.hamalog v2
http://d.hatena.ne.jp/hokaccha/20110805/1312544911

Mongoose で MongoDB の Embedded Documents の扱いで嵌まったこと - tilfin's note
http://tilfin.hatenablog.com/entry/20111030/1319966988

26
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?