从两个集合中填充

Populate from two collections

我为 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);

根据 mongoose populate documentation,这是要走的路。当我使用 Postman 获取电台时,我遇到的问题是 "Tripcount" 仍然是 []

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

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

对于 'trips' 集合:

{
    "_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);
        });
    });

};

我好像找不到错误,也许这里有人能发现我犯的错误。

您正在圈养猫鼬 SchemaTypes in single quotes, you either need to reference the SchemaTypes directly when you define a property in your documents which will be cast to its associated SchemaType

例如,当您在 tripSchema 中定义 Tripcount 时,它应该被转换为 Number SchemaType as

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 }] }
});