2016-08-03 4 views
0

あなたは、次のデータ構造を持っていますか?マングースは、コレクション内のオブジェクトを参照する場合は

したい動作を取得するために
const Item = mongoose.model('Item', mongoose.Schema({ 
    name: String, 
    branch: {type: mongoose.Schema.ObjectId, ref: 'Company.branches'} 
})); 
+0

会社のモデルのすべてのブランチにアクセスするのか、いくつかの基準に基づいて特定のブランチだけにアクセスしますか? –

+0

'Item'エンティティに格納されたブランチの' _id'に基づいて、ただ1つのブランチが必要です。 –

答えて

0

、あなたは別の支店のモデルを作成することができ、その後、あなたのアイテムのモデルは次のようになります。

const Item = mongoose.model('Item', mongoose.Schema({ 
    name: String, 
    branch: {type: mongoose.Schema.ObjectId, ref: 'Branch'} 
})); 

あなたの会社のスキーマはまた次のようになります。

const branchSchema = mongoose.Schema({ name: String }); 
const Company = mongoose.model('Company', mongoose.Schema({ 
    name: String, 
    branches: [{type: mongoose.Schema.ObjectId, ref: 'Branch'}] 
})); 

次に、検索を実行するときにブランチに関連する情報を取得するには、.populate()を使用します。

関連する問題