2014-02-22 116 views
0

我有一個集合,它有一個引用另一個集合的objectId的屬性。Mongoose populate()返回對象數組而不是單個對象

placeSchema = mongoose.Schema({ 
    name: String, 
    category: [{ type: Schema.Types.ObjectId, ref: 'categories' }], 
    facilities: [{ type: Schema.Types.ObjectId, ref: 'facilities' }], 
}); 

category REF爲categories集合的OBJECTID。 facilities ref是facilities集合的objectId的數組。

當我填充屬性,成爲facilities和陣列facilities objecrts的但category也變得之一單category陣列。

Place.find(query).populate('category').populate('facilities').limit(limit).skip(offset).exec(function(err, data){ 
    if (err) return handleError(err); 
    res.json(data); 
}); 

下面是上面查詢的例子:

{ 
    "_id": "52ff59be70e8f0dfc8358cb4", 
    "address": { 
     "address_1": "Chambers Street", 
     "city": "Edinburgh", 
     "postcode": "EH1 1JF" 
    }, 
    "description": "The National Museum of Scotland brings together our rich Scottish heritage with exciting international collections.", 
    "loc": { 
     "lon": -3.188384, 
     "lat": 55.94772 
    }, 
    "name": "National Museum of Scotland", 
    "facilities": [ 
     { 
      "_id": "53012d5b65b5e9a35efbb214", 
      "name": "Facility One" 
     }, 
     { 
      "_id": "53012d6965b5e9a35efbb215", 
      "name": "Facility Two" 
     } 
    ], 
    "category": [ 
     { 
      "_id": "52ffbf33605d0c81f36d98e0", 
      "name": "Museums", 
      "slug": "museums" 
     } 
    ] 
} 

這裏的文件,因爲它是在蒙戈:

{ 
    "_id" : ObjectId("52ff59be70e8f0dfc8358cb4"), 
    "address" : { 
     "address_1" : "Chambers Street", 
     "city" : "Edinburgh", 
     "postcode" : "EH1 1JF" 
    }, 
    "category" : ObjectId("52ffbf33605d0c81f36d98e0"), 
    "description" : "The National Museum of Scotland brings together our rich Scottish heritage with exciting international collections.", 
    "facilities" : [ 
     ObjectId("53012d5b65b5e9a35efbb214"), 
     ObjectId("53012d6965b5e9a35efbb215") 
    ], 
    "loc" : { 
     "lon" : -3.188384, 
     "lat" : 55.94772 
    }, 
    "name" : "National Museum of Scotland" 
} 

如何填充我的單category裁判,而不是一個數組?

回答

1

它使你既然感模式定義都宣稱類別字段是一個數組:

category: [{ type: Schema.Types.ObjectId, ref: 'categories' }] 

下應努力不把它放在一個數組(去掉[]):

category: { type: Schema.Types.ObjectId, ref: 'categories' } 

這是假設你確實只想要一個類別。

+0

我只是認爲它需要一個數組,我並沒有真正認爲這決定了結果。衛生署!謝謝安德烈亞斯! – iamjonesy

相關問題