2015-11-09 83 views
1

我是新來蒙戈DB /貓鼬創造人際關係簡單的解釋,這個問題是關於貓鼬和集合之間的關係,我知道有一個關於如何使這項工作,但仍然無法理解很多教程一個簡單的方法來完成這項工作。我有兩個型號:如何與貓鼬

這是主要的模式:

 'use strict'; 

     var mongoose = require('mongoose'), 
      Schema = mongoose.Schema; 

       var CategorySchema = new Schema({ 
        name : String, 
        info : String, 
        items : [{ type: Schema.Types.ObjectId, ref: 'Item' }] 
       }); 

       var itemsSchema = Schema({ 
        name  : String, 
        description : String, 
        price  : Number 
       }); 


     var Item = mongoose.model('Item', itemsSchema); 

     module.exports = mongoose.model('Category', CategorySchema); 

我需要填充類集合內項目數組並創建兩個集合之間的關係。

當我從郵遞員後我能看到的物品陣列越來越創建,但我不能填充陣列。

如果我得到的類別,這是響應:

[ 
     { 
      "_id": "564120be4123198a1f93feb5", 
      "name": "Classic", 
      "info": "this is the info", 
      "__v": 0, 
      "items": [] 
     }, 
     { 
      "_id": "5641220b02968e901f678ff5", 
      "name": "Classic", 
      "info": "this is the info", 
      "__v": 0, 
      "items": [] 
     } 
     ] 

這是看跌結果API /分類/

 { 
     "_id": "564120be4123198a1f93feb5", 
     "name": "test again", 
     "info": "this is the info", 
     "__v": 1, 
     "items": [] 
     } 

所需的輸出:

 { 
     "_id": "564120be4123198a1f93feb5", 
     "name": "test again", 
     "info": "this is the info", 
     "__v": 1, 
     "items": [ 
      { 
      "_id": "some id" 
      "name": "name", 
      "description": "lorem ipsup" 
      }, 
      { 
      "_id": "some id" 
      "name": "name", 
      "description": "lorem ipsup" 
      }, 
      { 
      "_id": "some id" 
      "name": "name", 
      "description": "lorem ipsup" 
      }, 
     ] 
     } 
+1

您使用什麼邏輯將項目插入類別? –

+0

@KevinB我需要有將來刪除單個項目的能力。 – user1547007

+0

你用什麼邏輯將項目插入類別?如果它工作正常,你應該在該數組中看到一個id。我沒有看到任何ID。 –

回答

0

即使如果您在類別中有參考,則應使用populate方法告知貓鼬您希望他檢索引用的項目。

喜歡的東西:

var Category = require('./category.model'); 
Category.find().populate("items"); 

如果要填充只有一個項目模型的領域,你可以將其添加INE填入的參數:

Category.find().populate("items","name"); 

我不知道你想什麼實現,但在我看來,另一種方式可能更有益(將類別引用到項目模型中)。