Search code examples
node.jsmongodbmongoosemongoose-populate

Mongoose populate with 2 Files and 2 Collections return empty array


I have the problem that my populate query returns an empty array. I am aware of the countless posts, however none of them provided new insights for me.

My first Schema: station.js

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

My second: trips.js

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

And my query looks like this, according to the majority of the answers this should do the job:

var Station = require('./station.js');
var query = Station.find()
        .populate({
            path: 'Tripcount',
            model : 'Tripcount'
        });
        query.exec(function(err, stations){
            if(err)
                res.send(err);
            res.json(stations);
        });

Using Postman to GET the stations, it shows Tripcount: []. Any ideas what I am doing wrong?


Solution

  • I thought I would add another answer based on previous comments. It seems that your data is not linking up. Mongoose populate will take the values in Station's Tripcount array and try and lookup the Tripcount object in the Tripcount collection using the _id field so lets say you have the following station

    {
      _id: 1,
      Tripcount: [100, 101, 102]
    }
    

    In your Tripcount Collection you will need the following to match up with the Station Above

    [
      {
        _id: 100,
        Tripcount: 2
      },
      {
        _id: 101,
        Tripcount: 4
      },
      {
        _id: 102,
        Tripcount: 6
      },
    ]
    

    Then when you run your query you will get the following

    {
      _id: 1,
      Tripcount: [
        {
          _id: 100,
          Tripcount: 2
        },
        {
          _id: 101,
          Tripcount: 4
        },
        {
          _id: 102,
          Tripcount: 6
        },
      ]
    }