2017-05-03 58 views
1

我有2個不同的集合定義的2級架構,我需要填充其中的一個到另一個:填充來自兩個集合

stationmodel.js

var stationSchema = new Schema({ 
    StationName: 'string', 
    _id: 'number', 
    Tripcount: [{ type: Schema.Types.ObjectId, ref: 'Tripcount'}] 
}, 
    {collection: 'stations'} 
); 
module.exports = mongoose.model('Station', stationSchema); 

tripmodel.js

var tripSchema = new Schema({ 
    _id: { type: Number, ref: 'Station'}, 
    Tripcount: 'number' 
}, 
    {collection: 'trips'} 
); 
module.exports = mongoose.model('Tripcount', tripSchema); 

根據貓鼬填充documentation,這是要走的路。當我使用Postman獲取電臺時,我遇到了「Tripcount」仍然爲[]的問題。

我的數據庫結構的 '站' 集合:

{ 
    "_id": 1, 
    "StationName": "Station A", 
} 

而對於 '旅行' 收藏:

{ 
    "_id": 1, 
    "Tripcount": 6 
} 

我routes.js:

module.exports = function(app) { 

    app.get('/stations', function(req,res) { 
     var query = Station.find().populate('Tripcount'); 
     query.exec(function(err, stations){ 
      if(err) 
       res.send(err); 
      res.json(stations); 
     }); 
    }); 

}; 

我可以似乎沒有發現錯誤,也許有人在這裏可以發現我犯的一個錯誤。

回答

1

您封閉貓鼬SchemaTypes在單引號,您可能需要直接引用SchemaTypes當你定義在文檔屬性將被轉換爲與其相關的SchemaType

例如,當你定義在tripSchemaTripcount應該投給Number的SchemaType作爲

var tripSchema = new Schema({ 
    _id: Number, 
    Tripcount: Number 
}, {collection: 'trips'}); 

module.exports = mongoose.model('Tripcount', tripSchema); 

和站模式

var stationSchema = new Schema({ 
    _id: Number, 
    StationName: String, 
    Tripcount: [{ type: Number, ref: 'Tripcount'}] 
}, {collection: 'stations'}); 

module.exports = mongoose.model('Station', stationSchema); 

然後在你的stations收集,文件將理想地具有結構

{ 
    "_id": 1, 
    "StationName": "Station A", 
    "Tripcount": [1] 
} 

的填入方法工作,其中當施加

Station.find().populate('Tripcount').exec(function(err, docs){ 
    if (err) throw err; 
    console.log(docs); 
    // prints { "_id": 1, "StationName": "Station A", "Tripcount": [{"_id": 1, Tripcount: 6 }] } 
}); 

另類視角

另一種方法,如果站收集沒有Tripcount場是,你可以採取使用在彙總框架中找到的$lookup運算符:

Station.aggregate([ 
    { 
     "$lookup": { 
      "from": "tripcollection", 
      "localField": "_id", 
      "foreignField": "_id", 
      "as": "trips" 
     } 
    }, 
    { 
     "$project": { 
      "StationName": 1, 
      "trips": { "$arrayElemAt": ["$trips", 0] } 
     } 
    }, 
    { 
     "$project": { 
      "StationName": 1, 
      "Tripcount": "$trips.Tripcount" 
     } 
    } 
]).exec(function(err, docs){ 
    if (err) throw err; 
    console.log(docs); 
    // prints [{ "_id": 1, "StationName": "Station A", "Tripcount": 6 }] } 
}); 
+0

謝謝。我根據你的建議改變了一切,然而郵差仍然顯示'Tripcount:[]'的一切。我把我改變的routes.js放在我的問題中。 – ffritz

+0

我認爲這涉及到「貓鼬填充空陣列」問題的人也有。 – ffritz

+0

我已經添加了一個替代方案,您可以嘗試,前提是「工作臺」收集與'_id'鍵的'trips'收集有關。 – chridam