从两个集合中填充

时间:2017-05-03 14:14:18

标签: node.js mongodb mongoose mongoose-populate

我为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”仍为[]的问题。

'station'集合的我的数据库结构:

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

对于'trip'系列:

{
    "_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 个答案:

答案 0 :(得分:1)

您将mongoose SchemaTypes括在单引号中,当您在文档中定义属性并将其转换为关联的SchemaTypes时,您需要直接引用SchemaType

例如,当您在Tripcount中定义tripSchema时,它应该转换为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 }] }
});