Wednesday, 3 May 2017

Populate from two collections

I have 2 Schemas defined for 2 different collections, and I need to populate one of them into the other:

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

According to the mongoose populate documentation, this is the way to go. I have the problem that "Tripcount" remains as [] when I use Postman to GET the stations.

My DB Structure for the 'stations' collection:

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

And for the 'trips' collection:

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

I can't seem to find the error, maybe someone here can spot a mistake I made.



via ffritz

No comments:

Post a Comment