mongoose
モンゴース人口
サーチ…
構文
- Query.populate(パス、[選択]、[モデル]、[一致]、[オプション])
パラメーター
| パラメータ | 説明 |
|---|---|
| パス | < Object、String >入力するパスまたはすべてのパラメータを指定するオブジェクトのいずれか |
| [選択] | < Object、String >集団クエリーのフィールド選択( '-id'を使用してidフィールドを'-id'すべてを含めることができます) |
| [モデル] | < Model > populationに使用するモデル。指定されていない場合、populateはスキーマのrefフィールドに名前でモデルをルックアップします。 |
| [一致] | < Object >集団の条件 |
| [オプション] | < Object >集団クエリー(ソートなど)のオプション |
単純なマングースの例
.populate()を使用すると、現在のコレクションまたはドキュメントにある参照を、そのコレクションの情報で埋め込むことができます。以前は混乱しているかもしれませんが、例が混乱を解消するのに役立つと思います。
次のコードは、UserとPostという2つのコレクションを作成します。
var mongoose = require('mongoose'),
Schema = mongoose.Schema
var userSchema = Schema({
name: String,
age: Number,
posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
});
var PostSchema = Schema({
user: { type: Schema.Types.ObjectId, ref: 'User' },
title: String,
content: String
});
var User = mongoose.model('User', userSchema);
var Post = mongoose.model('Post', postSchema);
すべてのユーザーを.find({})ときに各ユーザーのすべての投稿を作成する場合は、次の操作を実行できます。
User
.find({})
.populate('posts')
.exec(function(err, users) {
if(err) console.log(err);
//this will log all of the users with each of their posts
else console.log(users);
})
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow