2017-05-03 42 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